Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CSHARP

Squares of a Sorted Array

public class Solution {
    // [-4,-1,0,3,10]
    // [3]
    public int[] SortedSquares(int[] nums) {
        if (nums == null)
        {
            return null;
        }
        
        int[] newArray = new int[nums.Length];
        int left = 0; // 2
        int right = nums.Length - 1; // 1
        for (int i = nums.Length - 1; i >= 0; i--) // 0
        {
            int leftSq = nums[left] * nums[left]; // 0
            int rightSq = nums[right] * nums[right]; // 0
            if (leftSq > rightSq)
            {
                newArray[i] = leftSq;
                left++;
            }
            else
            {
                newArray[i] = rightSq;
                right--;
            }
        }
        
        // [0,1,9,16,100]
        return newArray;
    }
}
Source by leetcode.com #
 
PREVIOUS NEXT
Tagged: #Squares #Sorted #Array
ADD COMMENT
Topic
Name
4+8 =