暴搜
public int[] maxSlidingWindow(int[] nums, int k) {
if(k==1){
return nums;
}
int[] res = new int[nums.length-k+1];
for(int i=0;i<=nums.length-k;i++){
int max = nums[i];
for(int j=i;j<i+k;j++){
if(nums[j]>max){
max=nums[j];
}
}
res[i]=max;
}
return res;
}
暴搜+堆优化
public static int[] maxWindowHeap(int[] nums, int k) {
if(k == 1){
return nums;
}
int len = nums.length;
int[] res = new int[len-k+1];
for(int i=0;i<=len-k;i++) {
Queue<Integer> queue = new PriorityQueue<>(k,(o1,o2)->(o2-o1));
for(int j=i;j<i+k;j++) {
queue.add(nums[j]);
}
res[i]=queue.peek();
}
return res;
}
单调队列
队列里面存储的是数组的下标,注意判断条件时的书写
public static int[] maxWindowDeque(int[] nums, int k) {
if(k==1 || nums.length==0 || nums==null){
return nums;
}
int len = nums.length;
int[] res = new int[len-k+1];
int idx = 0;
LinkedList<Integer> queue = new LinkedList<>();
for(int i=0;i<len;i++) {
while(!queue.isEmpty() && nums[queue.peekLast()]<=nums[i]){
queue.pollLast();
}
queue.addLast(i);
if(queue.peekFirst()==(i-k)){
queue.pollFirst();
}
if(i>=k-1){
res[idx++]=nums[queue.peekFirst()];
}
}
return res;
}