暴力解法:
思路极其简单,先把数组中的所有元素平方,然后重新排序就行了
public static int[] sortedSquares(int[] nums) {
for (int i = 0; i < nums.length; i++) {
nums[i] = nums[i] * nums[i];
}
Arrays.sort(nums);
return nums;
}
双指针解法
平方后的数字的大小取决于原数的绝对值,绝对值大的数字分布在最左边和最右边
//双指针解法
public static int[] sortedSquares(int[] nums) {
//平方后的数字的大小取决于原数的绝对值,绝对值大的数字分布在最左边和最右边
int left = 0;
int right = nums.length - 1;
int[] result = new int[nums.length];
int i = result.length - 1;
while (left <= right) {
if (Math.abs(nums[left]) >= Math.abs(nums[right])) {
result[i--] = nums[left] * nums[left];
left++;
} else {
result[i--] = nums[right] * nums[right];
right--;
}
}
return result;
}