-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.go
60 lines (53 loc) · 1001 Bytes
/
Solution.go
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
type BinaryIndexedTree struct {
n int
c []int
}
func newBinaryIndexedTree(n int) *BinaryIndexedTree {
c := make([]int, n+1)
return &BinaryIndexedTree{n, c}
}
func (this *BinaryIndexedTree) update(x, delta int) {
for x <= this.n {
this.c[x] += delta
x += x & -x
}
}
func (this *BinaryIndexedTree) query(x int) int {
s := 0
for x > 0 {
s += this.c[x]
x -= x & -x
}
return s
}
type MRUQueue struct {
q []int
tree *BinaryIndexedTree
}
func Constructor(n int) MRUQueue {
q := make([]int, n+1)
for i := 1; i <= n; i++ {
q[i] = i
}
return MRUQueue{q, newBinaryIndexedTree(n + 2010)}
}
func (this *MRUQueue) Fetch(k int) int {
l, r := 1, len(this.q)
for l < r {
mid := (l + r) >> 1
if mid-this.tree.query(mid) >= k {
r = mid
} else {
l = mid + 1
}
}
x := this.q[l]
this.q = append(this.q, x)
this.tree.update(l, 1)
return x
}
/**
* Your MRUQueue object will be instantiated and called as such:
* obj := Constructor(n);
* param_1 := obj.Fetch(k);
*/