Sliding Window Maximum
题目链接:https://leetcode.com/problems...
这道题用deque,注意一下存的是index,因为要判断是否到最大的window值,是通过现在的index和deque第一个index的差来判断的。
public class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
if(nums == null || nums.length == 0 || k == 0) return new int[0];
/* result size: nums.length - k + 1
* deque: 1st element is the largest one, store the index !!
* 1. poll 1st element when 1st away from current = k
* 2. poll last element while last <= current, add current
* 3. put the 1st element into the result if index >= k - 1
*/
int[] result = new int[nums.length - k + 1];
Deque<Integer> deq = new LinkedList();
for(int i = 0; i < nums.length; i++) {
// step 1
if(!deq.isEmpty() && i - deq.peek() == k) deq.poll();
// step 2
while(!deq.isEmpty() && nums[deq.peekLast()] <= nums[i]) deq.pollLast();
deq.offer(i);
// step 3
if(i - k + 1 >= 0) result[i - k + 1] = nums[deq.peek()];
}
return result;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。