977. 有序数组的平方

[977.有序数组的平方 - 力扣(Leetcode)

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
29
30
31
32
33
34
35
36
37
38
//977有序数组的平方
class SquaresOfASortedArray977 {
public static void main(String[] args){
int[] arr = {-4,-1,0,3,10};
int[] res = sortedSquares(arr);
System.out.print("平方结果为:");
for (int item : res) {
System.out.print(item + "\t");
}
//0,1,9,16,100
}
//双指针法
public static int[] sortedSquares(int[] nums) {
int left = 0;
int right = nums.length - 1;
int[] res = new int[nums.length];

//我自己写的办法
// for(int i = res.length - 1;i >= 0;i--){
// if (nums[left] * nums[left] < nums[right] * nums[right]) {
// res[i] = nums[right] * nums[right--];
// }else {
// res[i] = nums[left] * nums[left++];
// }
// }

//另外一种办法
int i = res.length - 1;
while(left < right){
if (nums[left] * nums[left] < nums[right] * nums[right]) {
res[i--] = nums[right] * nums[right--];
}else {
res[i--] = nums[left] * nums[left++];
}
}
return res;
}
}