为了避免毕业后失业,还是要好好刷题,上次面试的时候问leetcode和剑指offer的比较多,去这里练习一下。
239. Sliding Window Maximum
Hard
127477FavoriteShare
Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window.
Example:
Input: nums =[1,3,-1,-3,5,3,6,7], and k = 3 Output:[3,3,5,5,6,7] Explanation:Window position Max --------------- ----- [1 3 -1] -3 5 3 6 7 3 1 [3 -1 -3] 5 3 6 7 3 1 3 [-1 -3 5] 3 6 7 5 1 3 -1 [-3 5 3] 6 7 5 1 3 -1 -3 [5 3 6] 7 6 1 3 -1 -3 5 [3 6 7] 7
Note:
You may assume k is always valid, 1 ≤ k ≤ input array's size for non-empty array.
题意:给一个数组,维护一个长度为K的滑动窗口,输出滑动过程窗口内的各个最大值。
思路:比较简单,用双端队列维护一个单调递减的单调队列,复杂度O(n)。
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
int len = nums.size();
vector<int>ans;
deque<pair<int,int>>q;
for(int i=0; i<len; ++i){
while(!q.empty() && i-q.front().first >= k) q.pop_front();
while(!q.empty() && nums[i] >= q.back().second) q.pop_back();
q.push_back(make_pair(i,nums[i]));
if(i >= k-1) ans.push_back(q.front().second);
}
return ans;
}
};
本文介绍了一种解决滑动窗口最大值问题的高效算法,使用双端队列维护一个单调递减的队列,实现O(n)的时间复杂度。通过实例解析,详细展示了算法的实现过程。
1007

被折叠的 条评论
为什么被折叠?



