-
Notifications
You must be signed in to change notification settings - Fork 3
/
AbsDistinct.java
39 lines (33 loc) · 989 Bytes
/
AbsDistinct.java
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
/*
Compute number of distinct absolute values of sorted array elements.
*/
class Solution {
public int solution(int[] A) {
int start = 0;
int N = A.length;
int end = N-1;
int count = 0;
while (start <= end) {
if (A[start] == Integer.MIN_VALUE) {
start++;
count++;
}
while (start < N-1 && A[start] == A[start+1]) start++;
int startVal = A[start] < 0 ? -A[start] : A[start];
while (end > 0 && A[end] == A[end-1]) end--;
int endVal = A[end] < 0 ? -A[end] : A[end];
if (startVal < endVal) {
end--;
count++;
} else if (startVal > endVal) {
start++;
count++;
} else {
start++;
end--;
count++;
}
}
return count;
}
}