mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 08:50:15 +08:00
Merge pull request #2322 from yunfeidog/master
Update0239滑动窗口最大值:存在单调队列并增加C++单调队列解法
This commit is contained in:
@ -64,7 +64,7 @@ public:
|
||||
|
||||
这么个队列香不香,要是有现成的这种数据结构是不是更香了!
|
||||
|
||||
**可惜了,没有! 我们需要自己实现这么个队列。**
|
||||
其实在C++中,可以使用 multiset 来模拟这个过程,文末提供这个解法仅针对C++,以下讲解我们还是靠自己来实现这个单调队列。
|
||||
|
||||
然后再分析一下,队列里的元素一定是要排序的,而且要最大值放在出队口,要不然怎么知道最大值呢。
|
||||
|
||||
@ -839,6 +839,28 @@ impl Solution {
|
||||
}
|
||||
```
|
||||
|
||||
### C++
|
||||
使用multiset作为单调队列
|
||||
|
||||
多重集合(`multiset`) 用以有序地存储元素的容器。允许存在相等的元素。
|
||||
|
||||
在遍历原数组的时候,只需要把窗口的头元素加入到multiset中,然后把窗口的尾元素删除即可。因为multiset是有序的,并且提供了*rbegin(),可以直接获取窗口最大值。
|
||||
```cpp
|
||||
class Solution {
|
||||
public:
|
||||
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
|
||||
multiset<int> st;
|
||||
vector<int> ans;
|
||||
for (int i = 0; i < nums.size(); i++) {
|
||||
if (i >= k) st.erase(st.find(nums[i - k]));
|
||||
st.insert(nums[i]);
|
||||
if (i >= k - 1) ans.push_back(*st.rbegin());
|
||||
}
|
||||
return ans;
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
<p align="center">
|
||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
||||
|
Reference in New Issue
Block a user