|
1 | 1 | class Solution { |
2 | 2 | public int[] sortedSquares(int[] nums) { |
3 | | - int n = nums.length; |
4 | | - int[] squareSorted = new int[n]; |
5 | | - int start = 0; |
6 | | - while (start < n && nums[start] < 0) { |
7 | | - start++; |
8 | | - } |
9 | | - int end = start; |
10 | | - start -= 1; |
11 | | - int idx = 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 | + int firstNegativeIdx = nums[0] < 0 ? 0 : nums.length; |
| 4 | + int lastPositiveIdx = nums[nums.length - 1] >= 0 ? nums.length - 1 : -1; |
| 5 | + int[] result = new int[nums.length]; |
| 6 | + int idx = 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 | | - } else if (start >= 0) { |
20 | | - squareSorted[idx++] = nums[start] * nums[start--]; |
| 22 | + } else if (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 | | - return squareSorted; |
| 30 | + return result; |
26 | 31 | } |
27 | 32 | } |
0 commit comments