class MajorityChecker {
public:
MajorityChecker(vector<int>& arr) {
}
int query(int left, int right, int threshold) {
}
};
/**
* Your MajorityChecker object will be instantiated and called as such:
* MajorityChecker* obj = new MajorityChecker(arr);
* int param_1 = obj->query(left,right,threshold);
*/
type MajorityChecker struct {
arr []int
loc map[int][]int
}
func Constructor(arr []int) MajorityChecker {
rand.Seed(time.Now().UnixNano())
loc := map[int][]int{}
for i, x := range arr {
loc[x] = append(loc[x], i)
}
return MajorityChecker{arr, loc}
}
func (mc *MajorityChecker) Query(left, right, threshold int) int {
length := right - left + 1
for i := 0; i < 20; i++ {
x := mc.arr[rand.Intn(right-left+1)+left]
pos := mc.loc[x]
occ := sort.SearchInts(pos, right+1) - sort.SearchInts(pos, left)
if occ >= threshold {
return x
}
if occ*2 >= length {
break
}
}
return -1
}
/**
* Your MajorityChecker object will be instantiated and called as such:
* obj := Constructor(arr);
* param_1 := obj.Query(left,right,threshold);
*/
class MajorityChecker:
k = 20
def __init__(self, arr: List[int]):
self.arr = arr
self.loc = defaultdict(list)
for i, val in enumerate(arr):
self.loc[val].append(i)
def query(self, left: int, right: int, threshold: int) -> int:
arr_ = self.arr
loc_ = self.loc
length = right - left + 1
for i in range(MajorityChecker.k):
x = arr_[randint(left, right)]
pos = loc_[x]
occ = bisect_right(pos, right) - bisect_left(pos, left)
if occ >= threshold:
return x
elif occ * 2 >= length:
return -1
return -1
# Your MajorityChecker object will be instantiated and called as such:
# obj = MajorityChecker(arr)
# param_1 = obj.query(left,right,threshold)