题解 | #滑动窗口的最大值#

滑动窗口的最大值

https://www.nowcoder.com/practice/1624bc35a45c42c0bc17d17fa0cba788

class Solution {
  public:
    vector<int> maxInWindows(const vector<int>& num, unsigned int size) {
        if (size > num.size() || size <= 0)
            return {};
        if (size == num.size())
            return {*max_element(num.begin(), num.end())};
        set<int, greater<int>> descendingSet;
        unordered_map<int, int> mymap;
        vector<int> myvect;
        int left = 0;
        int right = size - 1;
        for (int i = left; i <= right; i++) {
            mymap[num[i]]++;
            descendingSet.insert(num[i]);
        }
        function<int()> getEle = [&]() {
            int s = 0;
            for (auto& i : descendingSet) {
                s = i;
                break;
            }
            return s;
        };
        myvect.push_back(getEle());
        while (right < num.size() - 1) {
            mymap[num[left]]--;
            if (mymap[num[left]] <= 0)
                descendingSet.erase(num[left]);
            left++;
            descendingSet.insert(num[++right]);
            myvect.push_back(getEle());
        }
        return myvect;
    }
};

使用set<int, greater<int>> descendingSet;降序存储,逐个删除&增加

全部评论

相关推荐

点赞 评论 收藏
分享
马国成同志:如果是真大专的话 可以直接进厂 没必要搞简历 太正式了
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务