-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortedSquares.java
More file actions
37 lines (32 loc) · 1.04 KB
/
SortedSquares.java
File metadata and controls
37 lines (32 loc) · 1.04 KB
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
36
37
import java.util.*;
public class SortedSquares {
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;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Example: -7 -3 2 3 11
String[] input = sc.nextLine().split(" ");
int[] nums = new int[input.length];
for (int i = 0; i < input.length; i++) {
nums[i] = Integer.parseInt(input[i]);
}
int[] res = sortedSquares(nums);
System.out.println(Arrays.toString(res));
}
}