-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1395. Count number of teams
62 lines (46 loc) · 1.5 KB
/
1395. Count number of teams
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
//1395. Count number of teams
class Solution {
public int numTeams(int[] rating) {
int n = rating.length;
if(n < 3) {
return 0;
}
int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
for(int num : rating) {
min = Math.min(min, num);
max = Math.max(max, num);
}
int[] leftTree = new int[max - min + 2];
int[] rightTree = new int[max - min + 2];
for(int num : rating) {
update(rightTree, num - min, 1);
}
int count = 0;
for(int i = 0; i < n; i++) {
update(rightTree, rating[i] - min, -1);
int lessLeft = query(leftTree, rating[i] - min - 1);
int greaterLeft = i - lessLeft;
int lessRight = query(rightTree, rating[i] - min - 1);
int greaterRight = (n - i - 1) - lessRight;
count += lessLeft * greaterRight + greaterLeft * lessRight;
update(leftTree, rating[i] - min, 1);
}
return count;
}
private void update(int[] tree, int index, int value) {
index++;
while(index < tree.length) {
tree[index] += value;
index += index & (-index);
}
}
private int query(int[] tree, int index) {
int sum = 0;
index++;
while(index > 0) {
sum += tree[index];
index -= index & (-index);
}
return sum;
}
}