-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortedSquares.java
More file actions
36 lines (28 loc) · 914 Bytes
/
Copy pathSortedSquares.java
File metadata and controls
36 lines (28 loc) · 914 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package LeetcodePractice;
import java.util.Arrays;
public class SortedSquares {
public static void main(String[] args) {
int[] nums1 = {-4, -1, 0, 3, 10};
System.out.println(Arrays.toString(sortedSquares(nums1)));
int[] nums2 = {-7, -3, 2, 3, 11};
System.out.println(Arrays.toString(sortedSquares(nums2)));
}
public static int[] sortedSquares(int[] nums) {
int n = nums.length;
int[] result = new int[n];
int left = 0, right = n - 1;
int pos = n - 1;
while (left <= right) {
int leftSq = nums[left] * nums[left];
int rightSq = nums[right] * nums[right];
if (leftSq > rightSq) {
result[pos--] = leftSq;
left++;
} else {
result[pos--] = rightSq;
right--;
}
}
return result;
}
}