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;
    }
};
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 无法安睡总觉得需要梳理点什么需要释怀点什么 报社入职已经三个月有余,很幸运,第一个月被认可转正 但是接下来的两个月...
    禅心曼阅读 349评论 0 0