Sliding Window Maximum

Idea

How to effectively sort elements?

(logN) level sorting algorithms

How to slide the window while keep sorting effective?

Remove the first element, add the new tail element. So make sure REMOVE operation and INSERT operation is at optimal complexity.

My first choice is using a binary heap with logN insert and logN remove operations. Since Java has TreeSet implemented, I don't roll my own wheel.

Other trivial but essential implementation detail?

TreeSet using the Comparators compare logic to remove duplicates. see stack overflow

Thus you have to define a class that provides position information for each element so that when duplicated integers appear none of them will be missed to be added into the TreeSet.

class Element {
    public final int position;
    public final int value;
    public Element(int position, int value) {
        this.position = position;
        this.value = value;
    }
}

public class Solution {
    /*
     * @param nums: A list of integers
     * @param k: An integer
     * @return: The maximum number inside the window at each moving
     */
    public ArrayList<Integer> maxSlidingWindow(int[] nums, int k) {
        ArrayList<Integer> ans = new ArrayList<>();
        if (nums.length == 0) return ans;
        TreeSet<Element> tr = new TreeSet<>((e1, e2) -> {
            if (e1.value == e2.value) return (e1.position - e2.position);
            return e1.value - e2.value;
        });
        assert nums.length >= k;
        for(int i = 0; inclusiveEnd(i, k) < nums.length; i++) {
            if (i == 0) {
                for(int j = i; j <= inclusiveEnd(i, k); j++)
                  tr.add(new Element(j, nums[j]));
                ans.add(tr.last().value);
            } else {
                tr.remove(new Element(i - 1, nums[i - 1]));
                tr.add(new Element(inclusiveEnd(i, k), nums[inclusiveEnd(i, k)]));
                ans.add(tr.last().value);
            }
        }
        return ans;
    }
    
    private int inclusiveEnd(int i, int k) {
        return i + k - 1;
    }
};
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 無(wú)法安睡總覺(jué)得需要梳理點(diǎn)什么需要釋懷點(diǎn)什么 報(bào)社入職已經(jīng)三個(gè)月有余,很幸運(yùn),第一個(gè)月被認(rèn)可轉(zhuǎn)正 但是接下來(lái)的兩個(gè)月...
    禪心曼閱讀 396評(píng)論 0 0

友情鏈接更多精彩內(nèi)容