mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
update 0239.滑动窗口最大值.md about rust
This commit is contained in:
@ -802,6 +802,35 @@ class myDequeue{
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
rust:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
impl Solution {
|
||||||
|
pub fn max_sliding_window(nums: Vec<i32>, k: i32) -> Vec<i32> {
|
||||||
|
let mut res = vec![];
|
||||||
|
let mut queue = VecDeque::with_capacity(k as usize);
|
||||||
|
for (i, &v) in nums.iter().enumerate() {
|
||||||
|
// 如果队列长度超过 k,那么需要移除队首过期元素
|
||||||
|
if i - queue.front().unwrap_or(&0) == k as usize {
|
||||||
|
queue.pop_front();
|
||||||
|
}
|
||||||
|
while let Some(&index) = queue.back() {
|
||||||
|
if nums[index] >= v {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
// 如果队列第一个元素比当前元素小,那么就把队列第一个元素弹出
|
||||||
|
queue.pop_back();
|
||||||
|
}
|
||||||
|
queue.push_back(i);
|
||||||
|
if i >= k as usize - 1 {
|
||||||
|
res.push(nums[queue[0]]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
res
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||||
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
||||||
|
Reference in New Issue
Block a user