-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortedSquares977.java
More file actions
42 lines (36 loc) · 849 Bytes
/
SortedSquares977.java
File metadata and controls
42 lines (36 loc) · 849 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
38
39
40
41
public class SortedSquares977 {
public static void print(int[] data) {
int i = 0;
for(int a : data) {
System.out.println("[" + i + "] ... " + a);
i++;
}
}
public static void main(String[] args) {
int[] data = new int[] {4};
//int[] data = new int[] {-4,-1,0,3,10};
print(data);
int[] result = sortedSquares(data);
System.out.println();
print(result);
}
public static int[] sortedSquares(int[] A) {
int[] ret = new int[A.length];
int index = ret.length - 1;
int start = 0;
int end = index;
while( index >= 0 ) {
int value;
if(Math.abs(A[start]) > Math.abs(A[end])) {
value = A[start] * A[start];
start++;
}
else {
value = A[end] * A[end];
end--;
}
ret[index--] = value;
}
return ret;
}
}