mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
Update0239滑动窗口最大值:存在单调队列并增加C++单调队列解法
This commit is contained in:
@ -65,6 +65,10 @@ public:
|
||||
这么个队列香不香,要是有现成的这种数据结构是不是更香了!
|
||||
|
||||
**可惜了,没有! 我们需要自己实现这么个队列。**
|
||||
> 其实有这种数据结构的,在C++中,可以使用可以使用multiset这种数据结构作为单调队列
|
||||
> + 多重集合(`multiset`) 用以有序地存储元素的容器。允许存在相等的元素。
|
||||
>
|
||||
> 在遍历原数组的时候,只需要把窗口的头元素加入到multiset中,然后把窗口的尾元素删除即可。因为multiset是有序的,并且提供了*rbegin(),可以直接获取窗口最大值。
|
||||
|
||||
然后再分析一下,队列里的元素一定是要排序的,而且要最大值放在出队口,要不然怎么知道最大值呢。
|
||||
|
||||
@ -839,6 +843,24 @@ impl Solution {
|
||||
}
|
||||
```
|
||||
|
||||
### C++
|
||||
使用multiset作为单调队列
|
||||
```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