Skip to content

Commit e3de53f

Browse files
authored
Update Squares of a Sorted Array.java
1 parent 1f6ead1 commit e3de53f

File tree

1 file changed

+14
-22
lines changed

1 file changed

+14
-22
lines changed

Easy/Squares of a Sorted Array.java

Lines changed: 14 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,18 @@
11
class Solution {
2-
public int[] sortedSquares(int[] nums) {
3-
int negativeIdx = 0;
4-
int positiveIdx = nums.length - 1;
5-
int[] result = new int[nums.length];
6-
int resultIdx = 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++;
12-
} else {
13-
result[resultIdx--] = nums[positiveIdx] * nums[positiveIdx];
14-
positiveIdx--;
2+
public int[] sortedSquares(int[] nums) {
3+
int n = nums.length;
4+
int start = 0;
5+
int end = n - 1;
6+
int[] result = new int[n];
7+
for (int i = n - 1; i >= 0; i--) {
8+
if (Math.abs(nums[start]) >= Math.abs(nums[end])) {
9+
result[i] = nums[start] * nums[start];
10+
start++;
11+
} else {
12+
result[i] = nums[end] * nums[end];
13+
end--;
14+
}
1515
}
16-
} else if (nums[negativeIdx] < 0 && nums[positiveIdx] < 0) {
17-
result[resultIdx--] = nums[negativeIdx] * nums[negativeIdx];
18-
negativeIdx++;
19-
} else {
20-
result[resultIdx--] = nums[positiveIdx] * nums[positiveIdx];
21-
positiveIdx--;
22-
}
16+
return result;
2317
}
24-
return result;
25-
}
2618
}

0 commit comments

Comments
 (0)