|
1 | 1 | classSolution {
|
2 | 2 | publicint[]sortedSquares(int[]nums) {
|
3 |
| -intn =nums.length; |
4 |
| -int[]squareSorted =newint[n]; |
5 |
| -intstart =0; |
6 |
| -while (start <n &&nums[start] <0) { |
7 |
| -start++; |
8 |
| - } |
9 |
| -intend =start; |
10 |
| -start -=1; |
11 |
| -intidx =0; |
12 |
| -while (start >=0 ||end <n) { |
13 |
| -if (start >=0 &&end <n) { |
14 |
| -if (nums[start] *nums[start] >nums[end] *nums[end]) { |
15 |
| -squareSorted[idx++] =nums[end] *nums[end++]; |
| 3 | +intfirstNegativeIdx =nums[0] <0 ?0 :nums.length; |
| 4 | +intlastPositiveIdx =nums[nums.length -1] >=0 ?nums.length -1 : -1; |
| 5 | +int[]result =newint[nums.length]; |
| 6 | +intidx =result.length -1; |
| 7 | +while (idx >=0) { |
| 8 | +if (firstNegativeIdx <nums.length &&lastPositiveIdx >=0) { |
| 9 | +if (Math.abs(nums[firstNegativeIdx]) >nums[lastPositiveIdx]) { |
| 10 | +result[idx--] =nums[firstNegativeIdx] *nums[firstNegativeIdx]; |
| 11 | +firstNegativeIdx++; |
| 12 | +if (firstNegativeIdx <nums.length &&nums[firstNegativeIdx] >=0) { |
| 13 | +firstNegativeIdx =nums.length; |
| 14 | + } |
16 | 15 | }else {
|
17 |
| -squareSorted[idx++] =nums[start] *nums[start--]; |
| 16 | +result[idx--] =nums[lastPositiveIdx] *nums[lastPositiveIdx]; |
| 17 | +lastPositiveIdx--; |
| 18 | +if (lastPositiveIdx >=0 &&nums[lastPositiveIdx] <0) { |
| 19 | +lastPositiveIdx = -1; |
| 20 | + } |
18 | 21 | }
|
19 |
| - }elseif (start >=0) { |
20 |
| -squareSorted[idx++] =nums[start] *nums[start--]; |
| 22 | + }elseif (firstNegativeIdx <nums.length &&lastPositiveIdx <0) { |
| 23 | +result[idx--] =nums[firstNegativeIdx] *nums[firstNegativeIdx]; |
| 24 | +firstNegativeIdx++; |
21 | 25 | }else {
|
22 |
| -squareSorted[idx++] =nums[end] *nums[end++]; |
| 26 | +result[idx--] =nums[lastPositiveIdx] *nums[lastPositiveIdx]; |
| 27 | +lastPositiveIdx--; |
23 | 28 | }
|
24 | 29 | }
|
25 |
| -returnsquareSorted; |
| 30 | +returnresult; |
26 | 31 | }
|
27 | 32 | }
|