Squares of a sorted array

Solution for leetcode 977

Golang solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
func sortedSquares(nums []int) []int {
    result := make([]int, len(nums))
    
    start := 0
    end := len(nums)-1
    index := len(nums)-1
    
    for start <= end {
        if(abs(nums[start]) >= abs(nums[end])) {
            result[index] = nums[start] * nums[start]
            start++
        } else {
            result[index] = nums[end] * nums[end]
            end--
        }
        index--
    }
    return result
}

func abs(x int) int {
    
    if(x < 0) {
        return x * -1;
    }
    
    return x
}

Java solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
    public int[] sortedSquares(int[] nums) {
        int[] result = new int[nums.length];
        
        int start = 0;
        int end = nums.length - 1;
        int index = nums.length - 1;
        while(start <= end) {
            if(abs(nums[start]) <= abs(nums[end])) {
                result[index] = nums[end] * nums[end];
                end--;
            }
            else {
                result[index] = nums[start] * nums[start];
                start++;
            }
            index--;
        }
        
        return result;
    }
    
    public int abs(int data)
    {
        return data < 0 ? data * -1 : data;
    }
}
Time complexity : O(N)
Space complexity : O(N)
What's on this Page