Array:给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值

2016-05-23  本文已影响597人  敲一手烂代码
public static ArrayList<Integer> maxInWindows(int[] num, int size) {
        ArrayList<Integer> arrayList = new ArrayList<Integer>();
        if (num==null||num.length==0||num.length<size||size==0) {
            return arrayList;
        }
        LinkedList<Integer> linkedList = new LinkedList<Integer>();
        for (int i = 0; i < num.length; i++) {
            while (!linkedList.isEmpty()&&num[linkedList.peekLast()]<num[i]) {
                linkedList.pollLast();
            }
            linkedList.addLast(i);
            if (linkedList.peekFirst()==i-size) {
                linkedList.pollFirst();
            }
            if (i>=size-1) {
                arrayList.add(num[linkedList.peekFirst()]);
            }
    
        }
        return arrayList;
    }
上一篇下一篇

猜你喜欢

热点阅读