题目描述
给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{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]}。
代码一
思想:利用大顶堆的排序功能,先压入数组最开始的前size个元素,对while里面的每次操作,找到最大值(大顶堆的根),然后向后滑动(出堆一个,入堆一个)
import java.util.PriorityQueue;
import java.util.Comparator;
import java.util.ArrayList;
public class Solution {
public PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(15,new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
// TODO Auto-generated method stub
return o2-o1;
}
});
public ArrayList<Integer> res = new ArrayList<Integer>();
public ArrayList<Integer> maxInWindows(int [] num, int size)
{
if(num==null||size<=0||size>num.length)return res;
int count=0;
for(;count<size;count++) {
maxHeap.offer(num[count]);
}
while(count<num.length) {//此时count=size
res.add(maxHeap.peek());
maxHeap.remove(num[count-size]);
maxHeap.offer(num[count]);
count++;
}
res.add(maxHeap.peek());
return res;
}
}
代码二
思路:很简单直接
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> maxInWindows(int [] num, int size)
{
ArrayList<Integer> arr = new ArrayList<Integer>();
if(size<=0)return arr;
for(int i=0;i<=num.length-size;i++) {
arr.add(maxvalue(num,i,size));
}
return arr;
}
public static int maxvalue(int[] arr,int left,int size) {
int temp = Integer.MIN_VALUE;
for(int i=left;i<left+size;i++) {
if(arr[i]>temp) {
temp=arr[i];
}
}
return temp;
}
}