class RangeFreqQuery {
public:
RangeFreqQuery(vector<int>& arr) {
}
int query(int left, int right, int value) {
}
};
/**
* Your RangeFreqQuery object will be instantiated and called as such:
* RangeFreqQuery* obj = new RangeFreqQuery(arr);
* int param_1 = obj->query(left,right,value);
*/
type RangeFreqQuery struct{ pos [1e4 + 1]sort.IntSlice }
func Constructor(arr []int) (q RangeFreqQuery) {
for i, value := range arr {
q.pos[value] = append(q.pos[value], i) // 统计 value 在 arr 中的所有下标位置
}
return
}
func (q *RangeFreqQuery) Query(left, right, value int) int {
p := q.pos[value] // value 在 arr 中的所有下标位置
return p[p.Search(left):].Search(right + 1) // 在下标位置上二分,求 [left,right] 之间的下标个数,即为 value 的频率
}
/**
* Your RangeFreqQuery object will be instantiated and called as such:
* obj := Constructor(arr);
* param_1 := obj.Query(left,right,value);
*/
class RangeFreqQuery:
def __init__(self, arr: List[int]):
# 数值为键,出现下标数组为值的哈希表
self.occurence = defaultdict(list)
# 顺序遍历数组初始化哈希表
n = len(arr)
for i in range(n):
self.occurence[arr[i]].append(i)
def query(self, left: int, right: int, value: int) -> int:
# 查找对应的出现下标数组,不存在则为空
pos = self.occurence[value]
# 两次二分查找计算子数组内出现次数
l = bisect_left(pos, left)
r = bisect_right(pos, right)
return r - l
# Your RangeFreqQuery object will be instantiated and called as such:
# obj = RangeFreqQuery(arr)
# param_1 = obj.query(left,right,value)