classMajorityChecker:# threshold过半最多只有一个def__init__(self, arr: List[int]):# 记录每个值出现的index
self.d = defaultdict(list)for i, v inenumerate(arr):
self.d[v].append(i)# 出现频率的统计(从大到小)
self.freq =sorted([(len(ids), value)for value, ids in self.d.items()], reverse =True)defquery(self, left:int, right:int, threshold:int)->int:for f, v in self.freq:if f < threshold:break
ids = self.d[v]
l = bisect_left(ids, left)
r = bisect_right(ids, right)if r - l >= threshold:return v
return-1# Your MajorityChecker object will be instantiated and called as such:# obj = MajorityChecker(arr)# param_1 = obj.query(left,right,threshold)
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
随机二分
classMajorityChecker:# threshold过半最多只有一个def__init__(self, arr: List[int]):# 记录每个值出现的index
self.arr = arr
self.d = defaultdict(list)for i, v inenumerate(arr):
self.d[v].append(i)# 出现频率的统计(从大到小)# self.freq = sorted([(len(ids), value) for value, ids in self.d.items()], reverse = True)defquery(self, left:int, right:int, threshold:int)->int:# 随机从[l, r]抽一个数# 如果存在答案,那么抽不到答案的概率小于0.5# 多次都抽不到答案,认为没有答案,返回-1
Round =30for _ inrange(Round):
choice = self.arr[random.randint(left, right)]
l = bisect_left(self.d[choice], left)
r = bisect_right(self.d[choice], right)if r - l >= threshold:return choice
return-1# Your MajorityChecker object will be instantiated and called as such:# obj = MajorityChecker(arr)# param_1 = obj.query(left,right,threshold)