public class Solution {
/**
* @param nums: A list of integers.
* @return: The maximum number inside the window at each moving.
*/
public ArrayList<Integer> maxSlidingWindow(int[] nums, int k) {
// write your code here
ArrayList<Integer> result = new ArrayList<>();
if (nums == null || nums.length == 0 || k <= 0) return result;
//Deque of indicies
Deque<Integer> deque = new ArrayDeque<>();
//index -> end pointer of the window
for (int index = 0; index < nums.length; index++) {
if (!deque.isEmpty() && deque.getFirst() < index - k + 1) {
deque.removeFirst();
}
while (!deque.isEmpty() && nums[index] >= nums[deque.getLast()]) {
deque.removeLast();
}
deque.addLast(index);
if (index >= k - 1) {
result.add(nums[deque.getFirst()]);
}
}
return result;
}
}
No comments:
Post a Comment