滑动窗口最大值

滑动窗口最大值

239.滑动窗口最大值

给你一个整数数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字。滑动窗口每次只向右移动一位。

返回 滑动窗口中的最大值 。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
int n=nums.size();
//优先队列中存储二元组(nums[i], i);
priority_queue<pair<int,int>> pq;
//初始将前k个元素放入到优先队列中
for(int i=0;i<k;i++){
pq.emplace(nums[i], i);
}
//存放最终结果
vector<int> res={pq.top().first};
//开始移动窗口
for(int i=k;i<n;i++){
//将下一个元素加入
pq.emplace(nums[i], i);
//当堆顶元素为滑动窗口最左侧的值,移出堆顶元素
while(pq.top().second <= i-k){
pq.pop();
}
res.push_back(pq.top().first);
}
return res;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import "container/heap"

// 定义优先队列元素
type Item struct {
value int // 元素值
index int // 元素索引
}

// 定义优先队列
type PriorityQueue []*Item

func (pq PriorityQueue) Len() int { return len(pq) }

func (pq PriorityQueue) Less(i, j int) bool {
// 最大堆,值大的优先级高
return pq[i].value > pq[j].value
}

func (pq PriorityQueue) Swap(i, j int) {
pq[i], pq[j] = pq[j], pq[i]
}

func (pq *PriorityQueue) Push(x interface{}) {
item := x.(*Item)
*pq = append(*pq, item)
}

func (pq *PriorityQueue) Pop() interface{} {
old := *pq
n := len(old)
item := old[n-1]
*pq = old[0 : n-1]
return item
}

func maxSlidingWindow(nums []int, k int) []int {
n := len(nums)
// 优先队列中存储二元组(nums[i], i)
pq := &PriorityQueue{}
heap.Init(pq)

// 初始将前k个元素放入到优先队列中
for i := 0; i < k; i++ {
heap.Push(pq, &Item{value: nums[i], index: i})
}

// 存放最终结果
res := []int{(*pq)[0].value}

// 开始移动窗口
for i := k; i < n; i++ {
// 将下一个元素加入
heap.Push(pq, &Item{value: nums[i], index: i})
// 当堆顶元素为滑动窗口最左侧的值,移出堆顶元素
for (*pq)[0].index <= i-k {
heap.Pop(pq)
}
res = append(res, (*pq)[0].value)
}

return res
}
-------------本文结束 感谢阅读-------------
0%