This is a place to put my clutters, no matter you like it or not, welcome here.
0%
239. Sliding Window Maximum
Posted onEdited onIn面試Views: Symbols count in article: 1.7kReading time ≈2 mins.
You are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position.
MaxQueue() { maxs = new LinkedList<>(); nums = new LinkedList<>(); }
void offer(int num) { nums.offer(num); // add method throws an exception and offer doesn't. while (!maxs.isEmpty() && maxs.peekLast() < num) { maxs.pollLast(); } maxs.offerLast(num); }
Integer poll() { Integer res = null; if (!nums.isEmpty()) { res = nums.poll(); if (res.equals(maxs.peekFirst())) { maxs.pollFirst(); } } return res; }
Integer getMax() { Integer res = null; if (!maxs.isEmpty()) { res = maxs.peekFirst(); } return res; } } public int[] maxSlidingWindow(int[] nums, int k) { int n = nums.length; int[] res = new int[n-k+1]; if (n == 0 || k == 0) { return new int[0]; } MaxQueue mq = new MaxQueue(); for (int i = 0; i < k; i++) { mq.offer(nums[i]); }
res[0] = mq.getMax(); for (int i = k; i < n; i++) { mq.poll(); mq.offer(nums[i]); res[i-k+1] = mq.getMax(); } return res; } }