Description:
Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.
Solution:
Time Complexity : O(n)
Space Complexity: O(n)
// Two pointer
var sortedSquares = function(A) {
let result = [];
// Left and right pointer
let l = 0;
let r = A.length - 1;
// Position to add squared number to A
let p = r;
// Add the higher number to the array and then decrease the pointer
while (l <= r) {
if (A[l] ** 2 > A[r] ** 2) {
result[p--] = A[l++] ** 2;
} else {
result[p--] = A[r--] ** 2;
}
}
return result;
};
Top comments (0)