Given an array of n integer with duplicate number, and a moving window(size k), move the window at each iteration from the start of the array, find the maximum number inside the window at each moving.
public class Solution {
/**
* @param nums: A list of integers.
* @return: The maximum number inside the window at each moving.
*/
private void inQueue(Deque<Integer> q, int num){
while(!q.isEmpty() && q.peekLast() < num){
q.pollLast();
}
q.offer(num);
}
private void outQueue(Deque<Integer> q, int num){
if(num == q.peekFirst()){
q.pollFirst();
}
}
public ArrayList<Integer> maxSlidingWindow(int[] nums, int k) {
// write your code here
int n = nums.length;
Deque<Integer> q = new ArrayDeque<Integer>();
ArrayList<Integer> ret = new ArrayList<Integer>();
if(n == 0)
return ret;
//只到k-1因为k开始需要取结果了,之前不需要取只需要加数字
for(int i = 0; i < k-1; i ++){
inQueue(q, nums[i]);
}
for(int i = k-1; i < n; i ++){
inQueue(q, nums[i]);
ret.add(q.peekFirst());
outQueue(q, nums[i-k+1]);
}
return ret;
}
}
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
if not nums:
return []
dq = collections.deque()
for i in range(k-1):
self.inQueue(dq, nums[i])#初始只到k-1,不到k,并且这里也要pop q if necessary
l = len(nums)
res = []
for i in range(k-1, l):
self.inQueue(dq, nums[i])
res.append(dq[0])
self.outQueue(dq, nums[i-k+1])
return res
def inQueue(self, dq:collections.deque, k: int):
while dq and dq[-1] < k:
dq.pop()
dq.append(k)
def outQueue(self, dq:collections.deque, k: int):
if dq[0] == k:
dq.popleft()