-
Notifications
You must be signed in to change notification settings - Fork 481
/
1157.go
56 lines (50 loc) · 1.01 KB
/
1157.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
type MajorityChecker struct {
data []int
indexs map[int][]int
}
func Constructor(arr []int) MajorityChecker {
var res MajorityChecker
res.indexs = make(map[int][]int)
for i, v := range arr {
res.data = append(res.data, v)
res.indexs[v] = append(res.indexs[v], i)
}
return res
}
func (this *MajorityChecker) Query(left int, right int, threshold int) int {
for i := 0; i < 8; i++ {
var num int
if right <= left {
num = this.data[right]
} else {
num = this.data[rand.Intn(right - left) + left]
}
l, r := 0, len(this.indexs[num])-1
for l < r {
mid := (l + r) >> 1
if this.indexs[num][mid] >= left {
r = mid
} else {
l = mid + 1
}
}
t1, t2 := l, 0
l, r = 0, len(this.indexs[num])-1
for l < r {
mid := (l + r + 1) >> 1
if this.indexs[num][mid] <= right {
l = mid
} else {
r = mid - 1
}
}
if this.indexs[num][l] <= right {
l++
}
t2 = l
if t2 - t1 >= threshold {
return num
}
}
return -1
}