-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSquaresSortedArray.java
More file actions
22 lines (21 loc) · 591 Bytes
/
SquaresSortedArray.java
File metadata and controls
22 lines (21 loc) · 591 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class SquaresSortedArray {
public static int[] sortedSquares(int[] nums) {
if (nums == null || nums.length == 0) {
return nums;
}
final int sz = nums.length;
int[] res = new int[sz];
int l = 0, r = sz - 1, i = sz - 1;
while (l <= r) {
int left = nums[l] * nums[l], right = nums[r] * nums[r];
if (left >= right) {
res[i--] = left;
l++;
} else {
res[i--] = right;
r--;
}
}
return res;
}
}