Problem
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 ofvaluein 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:
1 | Input |
Constraints:
1 <= arr.length <= 1051 <= arr[i], value <= 1040 <= left <= right < arr.length- At most
105calls will be made toquery
Analysis
这道题目是一道设计题,要求是题目给出一个数组,然后有一个查询函数query(int left, int right, int value),要求返回在[left, right]这个范围中value出现的次数。如果每次都把[left,right]遍历一遍,这个效率会很低,因此我们要换一种思路。
首先因为题目给出了value,我的思路就是能不能先用这个value减少一部分计算。我们可以用一个unordered_map存储每个value出现过的下标,存成一个数组。这样我需要处理的内容就不是[left, right],而是一个记录了下标的数组。然后问题就变成如何在这个数组中找到[left, right]这个区间包含了多少元素。这个不就是左边界和有边界的问题吗?果断二分!
计算出左右边界之后相减就是出现的次数。
Solution
无。
Code
1 | class RangeFreqQuery { |
Summary
这道题目突破口在于,如何在一个记录下标的数组中找一个区间,这种做法是在设计题中是非常常见的。这道题目的分享到这里,感谢你的支持!