|
1 | 1 | classSolution {
|
2 | 2 | publicint[]sortedSquares(int[]nums) {
|
3 |
| -intfirstNegativeIdx =nums[0] <0 ?0 :nums.length; |
4 |
| -intlastPositiveIdx =nums[nums.length -1] >=0 ?nums.length -1 : -1; |
| 3 | +intnegativeIdx =0; |
| 4 | +intpositiveIdx =nums.length -1; |
5 | 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 |
| - } |
| 6 | +intresultIdx =nums.length -1; |
| 7 | +while(resultIdx >=0) { |
| 8 | +if (nums[negativeIdx] <0 &&nums[positiveIdx] >=0) { |
| 9 | +if (Math.abs(nums[negativeIdx]) >nums[positiveIdx]) { |
| 10 | +result[resultIdx--] =nums[negativeIdx] *nums[negativeIdx]; |
| 11 | +negativeIdx++; |
15 | 12 | }else {
|
16 |
| -result[idx--] =nums[lastPositiveIdx] *nums[lastPositiveIdx]; |
17 |
| -lastPositiveIdx--; |
18 |
| -if (lastPositiveIdx >=0 &&nums[lastPositiveIdx] <0) { |
19 |
| -lastPositiveIdx = -1; |
20 |
| - } |
| 13 | +result[resultIdx--] =nums[positiveIdx] *nums[positiveIdx]; |
| 14 | +positiveIdx--; |
21 | 15 | }
|
22 |
| - }elseif (firstNegativeIdx <nums.length &&lastPositiveIdx <0) { |
23 |
| -result[idx--] =nums[firstNegativeIdx] *nums[firstNegativeIdx]; |
24 |
| -firstNegativeIdx++; |
| 16 | + }elseif (nums[negativeIdx] <0 &&nums[positiveIdx] <0) { |
| 17 | +result[resultIdx--] =nums[negativeIdx] *nums[negativeIdx]; |
| 18 | +negativeIdx++; |
25 | 19 | }else {
|
26 |
| -result[idx--] =nums[lastPositiveIdx] *nums[lastPositiveIdx]; |
27 |
| -lastPositiveIdx--; |
| 20 | +result[resultIdx--] =nums[positiveIdx] *nums[positiveIdx]; |
| 21 | +positiveIdx--; |
28 | 22 | }
|
29 | 23 | }
|
30 | 24 | returnresult;
|
|