?LeetCode刷題實戰(zhàn)239:滑動窗口最大值
You are given an array of integers 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.
示例
示例 1:
輸入:nums = [1,3,-1,-3,5,3,6,7], k = 3
輸出:[3,3,5,5,6,7]
解釋:
滑動窗口的位置 最大值
--------------- -----
[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
示例 2:
輸入:nums = [1], k = 1
輸出:[1]
示例 3:
輸入:nums = [1,-1], k = 1
輸出:[1,-1]
示例 4:
輸入:nums = [9,11], k = 2
輸出:[11]
示例 5:
輸入:nums = [4,-2], k = 2
輸出:[4]
解題
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
vector<int> result;
int n = nums.size();
if(n<k) return result;
deque<int> que;
for(int i=0;i<k;++i){
while(!que.empty() && nums[que.back()]<nums[i])
{
que.pop_back();
}
que.push_back(i);
}
result.push_back(nums[que.front()]);
for(int i=k;i<n;++i){
while(!que.empty() && nums[que.back()]<nums[i])
{
que.pop_back();
}
if(!que.empty() && i-que.front()>=k)
que.pop_front();
que.push_back(i);
result.push_back(nums[que.front()]);
}
return result;
}
};
LeetCode刷題實戰(zhàn)222:完全二叉樹的節(jié)點個數(shù)
LeetCode刷題實戰(zhàn)225:用隊列實現(xiàn)棧
LeetCode刷題實戰(zhàn)226:翻轉(zhuǎn)二叉樹
LeetCode刷題實戰(zhàn)227:基本計算器 II
LeetCode刷題實戰(zhàn)228:匯總區(qū)間
LeetCode刷題實戰(zhàn)229:求眾數(shù) II
LeetCode刷題實戰(zhàn)230:二叉搜索樹中第K小的元素
LeetCode刷題實戰(zhàn)232:用棧實現(xiàn)隊列
LeetCode刷題實戰(zhàn)233:數(shù)字 1 的個數(shù)
LeetCode刷題實戰(zhàn)235:二叉搜索樹的最近公共祖先
LeetCode刷題實戰(zhàn)236:二叉樹的最近公共祖先
LeetCode刷題實戰(zhàn)237:刪除鏈表中的節(jié)點
LeetCode刷題實戰(zhàn)238:除自身以外數(shù)組的乘積
