forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution2.py
38 lines (34 loc) · 1006 Bytes
/
Solution2.py
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
class BinaryIndexedTree:
def __init__(self, n: int):
self.n = n
self.c = [0] * (n + 1)
def update(self, x: int, v: int):
while x <= self.n:
self.c[x] += v
x += x & -x
def query(self, x: int) -> int:
s = 0
while x:
s += self.c[x]
x -= x & -x
return s
class Solution:
def numTeams(self, rating: List[int]) -> int:
nums = sorted(set(rating))
m = len(nums)
tree1 = BinaryIndexedTree(m)
tree2 = BinaryIndexedTree(m)
for v in rating:
x = bisect_left(nums, v) + 1
tree2.update(x, 1)
n = len(rating)
ans = 0
for i, v in enumerate(rating):
x = bisect_left(nums, v) + 1
tree1.update(x, 1)
tree2.update(x, -1)
l = tree1.query(x - 1)
r = n - i - 1 - tree2.query(x)
ans += l * r
ans += (i - l) * (n - i - 1 - r)
return ans