public int[] sortedSquares(int[] nums) {
int[] res = new int[nums.length];
int i = 0;
for (int x : nums) {
res[i++] = x * x;
}
Arrays.sort(res);
return res;
}
也可以采用双指针,由于数组是非递减顺序排序,所以,在数组的最左边或者最右边的元素的平方一定是最大的,往中间,越来越小,因此,可以创建一个新数组,从后往前填充。
public int[] sortedSquares(int[] nums) {
int[] ans = new int[nums.length];
int i = 0, j =nums.length - 1, k = nums.length - 1;
while(k >= 0) {
if(Math.abs(nums[i]) > Math.abs(nums[j])){
ans[k--] = nums[i] * nums[i++];
} else{
ans[k--] = nums[j] * nums[j--];
}
}
return ans;
}
原文:https://www.cnblogs.com/supercute/p/14965999.html