forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution2.py
31 lines (27 loc) · 829 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
class BinaryIndexedTree:
def __init__(self, n):
self.n = n
self.c = [0] * (n + 1)
def update(self, x, delta):
while x <= self.n:
self.c[x] += delta
x += x & -x
def query(self, x):
s = 0
while x:
s += self.c[x]
x -= x & -x
return s
class Solution:
def countOperationsToEmptyArray(self, nums: List[int]) -> int:
pos = {x: i for i, x in enumerate(nums)}
nums.sort()
ans = pos[nums[0]] + 1
n = len(nums)
tree = BinaryIndexedTree(n)
for k, (a, b) in enumerate(pairwise(nums)):
i, j = pos[a], pos[b]
d = j - i - tree.query(j + 1) + tree.query(i + 1)
ans += d + (n - k) * int(i > j)
tree.update(i + 1, 1)
return ans