-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathSquaresOfASortedArray.java
More file actions
42 lines (36 loc) · 1.01 KB
/
SquaresOfASortedArray.java
File metadata and controls
42 lines (36 loc) · 1.01 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
38
39
40
41
42
package array;
// Source : https://leetcode.com/problems/squares-of-a-sorted-array/
// Id : 977
// Author : Fanlu Hai | https://github.com/Fanlu91/FanluLeetcode
// Date : 2019-06-04
// Topic : Array
// Level : Easy
// Other :
// Tips :
// Result : 100.00% 96.27%
public class SquaresOfASortedArray {
public int[] sortedSquares(int[] A) {
if (A == null)
return A;
int head = 0, tail = A.length - 1;
int s1 = A[head] * A[head], s2 = A[tail] * A[tail];
int[] result = new int[A.length];
int rIndex = tail;
while (rIndex > -1) {
if (s1 > s2) {
result[rIndex] = s1;
head++;
s1 = A[head] * A[head];
} else {
result[rIndex] = s2;
// mind the corner case
if (tail == 0)
break;
tail--;
s2 = A[tail] * A[tail];
}
rIndex--;
}
return result;
}
}