题解 | #滑动窗口的最大值#
滑动窗口的最大值
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;降序存储,逐个删除&增加