Range Frequency Queries
作者:互联网
Design a data structure to find the frequency of a given value in a given subarray.
The frequency of a value in a subarray is the number of occurrences of that value in the subarray.
Implement the RangeFreqQuery
class:
RangeFreqQuery(int[] arr)
Constructs an instance of the class with the given 0-indexed integer arrayarr
.int query(int left, int right, int value)
Returns the frequency ofvalue
in the subarrayarr[left...right]
.
A subarray is a contiguous sequence of elements within an array. arr[left...right]
denotes the subarray that contains the elements of nums
between indices left
and right
(inclusive).
Example 1:
Input ["RangeFreqQuery", "query", "query"] [[[12, 33, 4, 56, 22, 2, 34, 33, 22, 12, 34, 56]], [1, 2, 4], [0, 11, 33]] Output [null, 1, 2] Explanation RangeFreqQuery rangeFreqQuery = new RangeFreqQuery([12, 33, 4, 56, 22, 2, 34, 33, 22, 12, 34, 56]); rangeFreqQuery.query(1, 2, 4); // return 1. The value 4 occurs 1 time in the subarray [33, 4] rangeFreqQuery.query(0, 11, 33); // return 2. The value 33 occurs 2 times in the whole array.
Constraints:
1 <= arr.length <= 105
1 <= arr[i], value <= 104
0 <= left <= right < arr.length
- At most
105
calls will be made toquery
思路:reverted index,先收集每个元素出现的index,每个元素肯定是个递增的序列,那么可以用binarysearch或者用treemap,logn去搜,[1,4,7,9,10,24] 里面全部是index,然后用left去搜第一个大于left的index,在新array里面占第i,用right去搜最后一个小于right的index,在新array里面占第j,然后个数就是 j - i + 1; 这题要明确,treemap里面存的是什么;
class RangeFreqQuery {
//原来index, 在新list里面占的位置 index
private HashMap<Integer, TreeMap<Integer, Integer>> hashmap;
public RangeFreqQuery(int[] arr) {
this.hashmap = new HashMap<>();
for(int i = 0; i < arr.length; i++) {
if(!hashmap.containsKey(arr[i])) {
hashmap.put(arr[i], new TreeMap<Integer, Integer>());
}
hashmap.get(arr[i]).put(i, hashmap.get(arr[i]).size());
}
}
public int query(int left, int right, int value) {
if(!hashmap.containsKey(value)) {
return 0;
}
TreeMap<Integer, Integer> nums = hashmap.get(value);
Integer a = nums.ceilingKey(left);
Integer b = nums.floorKey(right);
if(a == null || b == null) {
return 0;
}
return nums.get(b) - nums.get(a) + 1;
}
}
/**
* Your RangeFreqQuery object will be instantiated and called as such:
* RangeFreqQuery obj = new RangeFreqQuery(arr);
* int param_1 = obj.query(left,right,value);
*/
标签:RangeFreqQuery,arr,right,int,value,Range,Frequency,Queries,left 来源: https://blog.csdn.net/u013325815/article/details/121469611