面试题59-题目一:滑动窗口的最大值

/*

 * 面试题59-题目一:滑动窗口的最大值

 * 题目:给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。

 * 例如,如果输入数组{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长度,由于存储的是下标,所以可以计算得到;     

 * 特别说明,我们在双端队列中保存的数字是传入的向量的下标

 * 时间复杂度on),空间复杂度为on

 */

 

import java.util.ArrayList;

import java.util.LinkedList;

 

public class No59maxInWindows {

 

    public static void main(String[] args) {

       No59maxInWindows n = new No59maxInWindows();

       ArrayList<Integer> res = new ArrayList<Integer>();

       int[] a = { 2, 3, 4, 2, 6, 2, 5, 1 }; 

       res = n.maxInWindows(a, 3); 

        System.out.print("最大值数组为:"); 

        for (int i = 0; i < res.size(); i++) { 

            System.out.print(res.get(i) + " "); 

        } 

    }

 

    public ArrayList<Integer> maxInWindows(int[] num, int size) {

       ArrayList<Integer> res = new ArrayList<Integer>();

      

       if (num == null || size < 1 || num.length < size) {

           return res;

       }

      

       LinkedList<Integer> qMax = new LinkedList<Integer>();// 定义一个双端队列,保持的时数组下标

      

       for (int i = 0; i < num.length; i++) {

           int cur = num[i];

           while (!qMax.isEmpty() && num[qMax.peekLast()] <= cur) {// 当双端队列不空,并且当前元素大于等于队列的尾的元素时

              qMax.pollLast();// 把队列尾部元素弹出

           }

           qMax.addLast(i);// 把当前数组下标存到队列中 

           if (qMax.peekFirst() == i - size) {// 当队首的元素下标为i-w时,过期 

               qMax.pollFirst();// 将队首元素弹出 

           }

          

           if (i >= size - 1) {// i=3size=3,此时窗口下标应为[1,2,3]index0,故此时index1,即窗口右移

              res.add(num[qMax.peekFirst()]);// 当前窗口的最大值,即窗口右移一位后的首部

           }

       }

      

       return res;

    }

 

}

猜你喜欢

转载自blog.csdn.net/juaner1993/article/details/82776602