Given an array of integers A
sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order.
Example 1:
Input: [-4,-1,0,3,10]
Output: [0,1,9,16,100]
Example 2:
Input: [-7,-3,2,3,11]
Output: [4,9,9,49,121]
思路:很巧妙,用双指针,因为有负数,所以平方之后,可能会变大,那么就判断i, j最前和最后的两个值,谁大,谁到最后;
class Solution {
public int[] sortedSquares(int[] A) {
if(A == null || A.length == 0) {
return A;
}
int n = A.length;
int[] result = new int[n];
int i = 0;
int j = n - 1;
for(int p = n - 1; p >= 0; p--) {
if(Math.abs(A[i]) > Math.abs(A[j])) {
result[p] = Math.abs(A[i]) * Math.abs(A[i]);
i++;
} else {
// Math.abs(A[i]) <= Math.abs(A[j])
result[p] = Math.abs(A[j]) * Math.abs(A[j]);
j--;
}
}
return result;
}
}