-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode977.java
More file actions
49 lines (45 loc) · 1.74 KB
/
LeetCode977.java
File metadata and controls
49 lines (45 loc) · 1.74 KB
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
39
40
41
42
43
44
45
46
47
48
49
import java.util.Arrays;
public class LeetCode977 {
public static void main(String[] args) {
// 输入:nums = [-4,-1,0,3,10]
// 输出:[0,1,9,16,100]
System.out.println(Arrays.toString(new Solution977().sortedSquares(new int[] { -4, -1, 0, 3, 10 })));
// 输入:nums = [-7,-3,2,3,11]
// 输出:[4,9,9,49,121]
System.out.println(Arrays.toString(new Solution977().sortedSquares(new int[] { -7, -3, 2, 3, 11 })));
}
}
class Solution977 {
public int[] sortedSquares(int[] nums) {
int[] result = new int[nums.length];
// 找到正数和负数的起始点
int positiveStart = nums.length;
for (int i = 0; i < nums.length; i++) {
if (nums[i] >= 0) {
positiveStart = i;
break;
}
}
int index = 0;
int negativeStart = positiveStart - 1;
while (negativeStart >= 0 || positiveStart < nums.length) {
if (negativeStart >= 0 && positiveStart == nums.length) {
result[index] = nums[negativeStart] * nums[negativeStart];
negativeStart--;
} else if (negativeStart < 0 && positiveStart < nums.length) {
result[index] = nums[positiveStart] * nums[positiveStart];
positiveStart++;
} else {
if (nums[positiveStart] <= -nums[negativeStart]) {
result[index] = nums[positiveStart] * nums[positiveStart];
positiveStart++;
} else {
result[index] = nums[negativeStart] * nums[negativeStart];
negativeStart--;
}
}
index++;
}
return result;
}
}