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;
}
};