题目描述

给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{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里面的每次操作,找到最大值(大顶堆的根),然后向后滑动(出堆一个,入堆一个)

  1. import java.util.PriorityQueue;
  2. import java.util.Comparator;
  3. import java.util.ArrayList;
  4. public class Solution {
  5. public PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(15,new Comparator<Integer>() {
  6. @Override
  7. public int compare(Integer o1, Integer o2) {
  8. // TODO Auto-generated method stub
  9. return o2-o1;
  10. }
  11. });
  12. public ArrayList<Integer> res = new ArrayList<Integer>();
  13. public ArrayList<Integer> maxInWindows(int [] num, int size)
  14. {
  15. if(num==null||size<=0||size>num.length)return res;
  16. int count=0;
  17. for(;count<size;count++) {
  18. maxHeap.offer(num[count]);
  19. }
  20. while(count<num.length) {//此时count=size
  21. res.add(maxHeap.peek());
  22. maxHeap.remove(num[count-size]);
  23. maxHeap.offer(num[count]);
  24. count++;
  25. }
  26. res.add(maxHeap.peek());
  27. return res;
  28. }
  29. }

代码二

思路:很简单直接

  1. import java.util.ArrayList;
  2. public class Solution {
  3. public ArrayList<Integer> maxInWindows(int [] num, int size)
  4. {
  5. ArrayList<Integer> arr = new ArrayList<Integer>();
  6. if(size<=0)return arr;
  7. for(int i=0;i<=num.length-size;i++) {
  8. arr.add(maxvalue(num,i,size));
  9. }
  10. return arr;
  11. }
  12. public static int maxvalue(int[] arr,int left,int size) {
  13. int temp = Integer.MIN_VALUE;
  14. for(int i=left;i<left+size;i++) {
  15. if(arr[i]>temp) {
  16. temp=arr[i];
  17. }
  18. }
  19. return temp;
  20. }
  21. }