?LeetCode刷題實(shí)戰(zhàn)239:滑動(dòng)窗口最大值
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]
解釋:
滑動(dòng)窗口的位置 最大值
--------------- -----
[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;
}
};
LeetCode1-220題匯總,希望對(duì)你有點(diǎn)幫助!
LeetCode刷題實(shí)戰(zhàn)221:最大正方形
LeetCode刷題實(shí)戰(zhàn)222:完全二叉樹的節(jié)點(diǎn)個(gè)數(shù)
LeetCode刷題實(shí)戰(zhàn)223:矩形面積
LeetCode刷題實(shí)戰(zhàn)224:基本計(jì)算器
LeetCode刷題實(shí)戰(zhàn)225:用隊(duì)列實(shí)現(xiàn)棧
LeetCode刷題實(shí)戰(zhàn)226:翻轉(zhuǎn)二叉樹
LeetCode刷題實(shí)戰(zhàn)227:基本計(jì)算器 II
LeetCode刷題實(shí)戰(zhàn)228:匯總區(qū)間
LeetCode刷題實(shí)戰(zhàn)229:求眾數(shù) II
LeetCode刷題實(shí)戰(zhàn)230:二叉搜索樹中第K小的元素
LeetCode刷題實(shí)戰(zhàn)231:2的冪
LeetCode刷題實(shí)戰(zhàn)232:用棧實(shí)現(xiàn)隊(duì)列
LeetCode刷題實(shí)戰(zhàn)233:數(shù)字 1 的個(gè)數(shù)
LeetCode刷題實(shí)戰(zhàn)234:回文鏈表
LeetCode刷題實(shí)戰(zhàn)235:二叉搜索樹的最近公共祖先
LeetCode刷題實(shí)戰(zhàn)236:二叉樹的最近公共祖先
LeetCode刷題實(shí)戰(zhàn)237:刪除鏈表中的節(jié)點(diǎn)
LeetCode刷題實(shí)戰(zhàn)238:除自身以外數(shù)組的乘積
