forked from luliyucoordinate/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1409.go
More file actions
37 lines (32 loc) · 718 Bytes
/
Copy path1409.go
File metadata and controls
37 lines (32 loc) · 718 Bytes
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
var N int
func processQueries(queries []int, m int) []int {
n := len(queries)
N = m + n + 1
pos := make([]int, m + 1)
tree := make([]int, n + m + 1)
for i := 1; i <= m; i++ {
pos[i] = n + i
update(tree, i + n, 1)
}
res := []int{}
for _, i := range queries {
res = append(res, prefixSum(tree, pos[i] - 1))
update(tree, pos[i], -1)
update(tree, n, 1)
pos[i] = n
n--
}
return res
}
func update(tr []int, x, v int) {
for i := x; i < N; i += i & -i {
tr[i] += v
}
}
func prefixSum(tr []int, x int) int {
res := 0
for i := x; i > 0; i -= i & -i {
res += tr[i]
}
return res
}