-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSquaresortedarray.java
More file actions
37 lines (31 loc) · 935 Bytes
/
Squaresortedarray.java
File metadata and controls
37 lines (31 loc) · 935 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
36
37
class Squaresortedarray {
public int[] sortedSquares(int[] nums) {
int [] ans = new int[nums.length];
int start = 0;
int end = nums.length - 1;
int ptr = ans.length - 1;
while(start <= end){
int ss = nums[start] * nums[start];
int es = nums[end] * nums[end];
if(ss > es){
ans[ptr] = ss;
start++;
}
else{
ans[ptr] = es;
end--;
}
ptr--;
}
return ans;
}
public static void main(String[] args) {
Squaresortedarray obj = new Squaresortedarray();
int[] nums = {-4, -1, 0, 3, 10};
int[] result = obj.sortedSquares(nums);
System.out.print("Sorted Squares: ");
for (int num : result) {
System.out.print(num + " ");
}
}
}