题目描述
给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{2,3,4,2,6,2,5,1}及滑动窗口的大小3,那么一共存在6个滑动窗口,他们的最大值分别为{4,4,6,6,6,5}; 针对数组{2,3,4,2,6,2,5,1}的滑动窗口有以下6个: {[2,3,4],2,6,2,5,1}, {2,[3,4,2],6,2,5,1}, {2,3,[4,2,6],2,5,1}, {2,3,4,[2,6,2],5,1}, {2,3,4,2,[6,2,5],1}, {2,3,4,2,6,[2,5,1]}。
解题:双指针法(Tcp滑动窗口)
用一个临时向量保存滑动窗口的值,sort之后挑出最大的push_back给res,之后plow++,phigh++寻找新的最大值
这道题也是滑动窗口的类型:https://www.cnblogs.com/cstdio1/p/11242623.html
注意临界的范围和超出界限的范围
c++代码如下:
class Solution { public: vector<int> maxInWindows(const vector<int>& num, unsigned int size) { vector<int> res; vector<int> tmp; if(num.empty()||size>num.size()||size<1) return res; int phigh=size,plow=0; while(phigh<=num.size()){ for(int i=plow;i<phigh;i++){ tmp.push_back(num[i]); } sort(tmp.begin(),tmp.end()); res.push_back(tmp[tmp.size()-1]); tmp.clear(); plow++; phigh++; }return res; } };
大根栈:
class Solution { public int[] maxSlidingWindow(int[] nums, int k) { if(nums.length==0) return new int[0]; Queue<Integer> pq = new PriorityQueue<>((v1, v2) -> v2 - v1); int len=nums.length; int []arr = new int[len-k+1]; int l=0,r=k-1,top=0; for(int i=l;i<=r;i++){ pq.offer(nums[i]); } while(r<=len){ arr[top++]=pq.peek(); pq.remove(nums[l]); l++;r++; if(r==len) break; pq.offer(nums[r]); } return arr; } }
按照c++代码的思路:
class Solution { public int[] maxSlidingWindow(int[] nums, int k) { if(nums.length==0) return new int[0]; int len=nums.length; int []arr = new int[len-k+1]; int l=0,r=k-1,top=0; while(r<=len){ int []tmp = new int[k]; for(int i=l;i<=r;i++){ tmp[i-l]=nums[i]; } Arrays.sort(tmp); arr[top++]=tmp[k-1]; l++;r++; if(r==len) break; } return arr; } }
Arrays.stream(nums,i,i+k).max().getAsInt();
class Solution { public int[] maxSlidingWindow(int[] nums, int k) { if (nums.length == 0) { return new int[]{}; } int len = nums.length + 1 - k; int[] res = new int[len]; for (int i = 0; i < len; i++) { res[i] = Arrays.stream(nums,i,i+k).max().getAsInt(); } return res; } }