Leetcode - Sliding Window Maximum

Given an array 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.

For example,
Given nums = [1,3,-1,-3,5,3,6,7], and k = 3.

Window position Max
--------------- -----
[1 3 -1] -3 5 3 6 7 3
1 [3 -1 -3] 5 3 6 7 3
1 3 [-1 -3 5] 3 6 7 5
1 3 -1 [-3 5 3] 6 7 5
1 3 -1 -3 [5 3 6] 7 6
1 3 -1 -3 5 [3 6 7] 7
Therefore, return the max sliding window as [3,3,5,5,6,7].
[分析] 首先要正确理解题意,结果是返回每个长度为k的窗口中的最大值。当窗口滑动一格时如何确定窗口中的最大值呢?直接的方法是遍历,则复杂度是O(k * n),选用最大堆存储窗口,则找到当前堆中最大值时O(1),窗口滑动时,需要添加一个新元素并删除窗口左边界元素,耗费为O(logk),因此总的复杂度是O(n*logk),当k很大时效率提升比较明显

更优的思路是使用Deque, 时间复杂度为O(N),之前都没用过这种数据结构,JDK文档上说ArrayDeque用作stack时比Stack数据结构快,用作queue时比LinkedList快,好东西呀~
参考
https://leetcode.com/discuss/46578/java-o-n-solution-using-deque-with-explanation



// Method 2: O(N), using Deque
public int[] maxSlidingWindow(int[] nums, int k) {
if (nums == null || nums.length == 0)
return new int[0];
int n = nums.length;
int[] max = new int[n - k + 1];
int idx = 0;
Deque<Integer> deque = new ArrayDeque<Integer>();
for (int i = 0; i < n; i++) {
if (!deque.isEmpty() && deque.peek() == i - k)
deque.pollFirst();
while (!deque.isEmpty() && nums[deque.peekLast()] <= nums[i])
deque.pollLast();
deque.offer(i);
if (i >= k - 1) max[idx++] = nums[deque.peek()];
}
return max;
}



// Method 1: O(N * logk), using PriorityQueue
public class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
if (nums == null)
return null;
if (nums.length == 0)
return new int[0];
int n = nums.length;
int[] result = new int[n - k + 1];
PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(k, new LargerComparator());
for (int i = 0; i < k; i++) {
maxHeap.offer(nums[i]);
}
result[0] = maxHeap.peek();
int start = 0;
for (int i = k; i < n; i++) {
maxHeap.offer(nums[i]);
maxHeap.remove(nums[start++]);
result[i - k + 1] = maxHeap.peek();
}
return result;
}
}
class LargerComparator implements Comparator<Integer> {
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值