生成窗口最大數組

題目

  有一個整形數組arr和一個大小爲w的窗口從數組的最左邊滑到最右邊,窗口每次向右邊滑一個位置。
  例如:數組爲[4,3,5,4,3,3,6,7],窗口大小爲3時:java

[4,3,5],4,3,3,6,7 5
4,[3,5,4],3,3,6,7 5
4,3,[5,4,3],3,6,7 5
4,3,5,[4,3,3],6,7 4
4,3,5,4,[3,3,6],7 6
4,3,5,4,3,[3,6,7] 7git

實現思路

  使用淘汰劣勢元素的方式進行實現,每一個元素有位置和值兩個屬性,使用隊列進行存儲,處理原則:github

  • 新加入的元素,使用值較大的優點,能夠淘汰已存儲在隊列中比他小的元素。
  • 新加入的元素,沒法淘汰隊列中比其大的元素,但新加入的元素有位置優點,那麼就須要排在大元素以後。
  • 每次移動窗口,隊頭不在窗口範圍內,須要淘汰。

  使用上面的思路進行實現,那麼每次移動窗口,隊頭的元素就是對大的值了。數組

實現代碼

package com.github.zhanyongzhi.interview.algorithm.stacklist;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * 獲取各個窗口的最大值
 */
public class GetWindowMax {
    public List<Integer> getWindowMax(Integer[] input, int windowSize) {
        Deque<Integer> maxIndexQueue = new LinkedList<Integer>();
        List<Integer> result = new ArrayList<>();

        for (int i = 0; i < input.length; i++) {
            if(maxIndexQueue.isEmpty()) {
                maxIndexQueue.push(i);
                continue;
            }

            //移除過時的索引
            if(maxIndexQueue.peekFirst() + 3 <= i)
                maxIndexQueue.removeFirst();

            //當前若是是最大的數,則刪除前面比其小的數字的索引,不然直接加到最後
            Integer lastElement = input[maxIndexQueue.peekLast()];
            Integer curElement = input[i];

            while(curElement >= lastElement){
                maxIndexQueue.removeLast();

                if(maxIndexQueue.isEmpty())
                    break;

                lastElement = input[maxIndexQueue.peekLast()];
            }

            maxIndexQueue.addLast(i);

            //索引未夠window size,不須要獲取最大值
            if(i < (windowSize - 1))
                continue;

            //最大值爲開頭的數字
            result.add(input[maxIndexQueue.peekFirst()]);
        }

        return result;
    }
}

在github中查看code

相關文章
相關標籤/搜索