Skip to content

Commit b980b29

Browse files
authored
Update Squares of a Sorted Array.java
1 parent 0eb294b commit b980b29

File tree

1 file changed

+23
-18
lines changed

1 file changed

+23
-18
lines changed

Easy/Squares of a Sorted Array.java

Lines changed: 23 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,32 @@
11
class Solution {
22
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+
}
1615
} 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+
}
1821
}
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++;
2125
} else {
22-
squareSorted[idx++] = nums[end] * nums[end++];
26+
result[idx--] = nums[lastPositiveIdx] * nums[lastPositiveIdx];
27+
lastPositiveIdx--;
2328
}
2429
}
25-
return squareSorted;
30+
return result;
2631
}
2732
}

0 commit comments

Comments
 (0)