力扣2080.区间内查询数字的频率

力扣2080.区间内查询数字的频率

题目

力扣2080.区间内查询数字的频率_第1张图片

题目解析及思路

题目要求求出[l,r]上val的出现次数

用哈希表把所有元素的所有下标存起来,在val的数组中分别对l,r二分找到在[l,r]内的下标数量

  • 在下标上做二分

    • 把所有下标存入哈希表
    • 在left,right的范围内做二分求个数

代码

class RangeFreqQuery {
    unordered_map<int, vector<int>> pos;
public:
    RangeFreqQuery(vector<int>& arr) {
        for(int i=0;i<arr.size();i++)
        {
            //将val的所有下标存下
            pos[arr[i]].push_back(i);
        }

    }
    
    int query(int left, int right, int value) {
        auto it = pos.find(value);
        if(it == pos.end()) return 0;
        //取val的数组
        auto &a = it->second;
        return ranges::upper_bound(a,right) - ranges::lower_bound(a,left);
    }
};

你可能感兴趣的:(leetcode,算法,职场和发展)