leetcode面试准备:Sliding Window Maximum

1 题目

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].

Note:

You may assume k is always valid, ie: 1 ≤ k ≤ input array's size for non-empty array.

Hint:

  1. How about using a data structure such as deque (double-ended queue)?
  2. The queue size need not be the same as the window’s size.
  3. Remove redundant elements and the queue should store only elements that need to be considered.

接口:public int[] maxSlidingWindow(int[] nums, int k)

2 思路

  1. Brute force solution is O(nw)

  2. Use heap, when window moves, delete the first one in the window, add the next one into the window. The run time complexity is O(n lg w).

  3. Use double-ended queue.

The obvious solution with run time complexity of O(nw) is definitely not efficient enough. Every time the window is moved, we have to search for the maximum from w elements in the window.

We need a data structure where we can store the candidates for maximum value in the window and discard the element, which are outside the boundary of window. For this, we need a data structure in which we can edit at both the ends, front and back. Deque is a perfect candidate for this problem.

We are trying to find a way in which, we need not search for maximum element among all in the window. We will make sure that the largest element in the window would always appear in the front of the queue.

While traversing the array in forward direction if we find a window where element A[i] > A[j] and i > j, we can surely say that A[j], will not be the maximum element for this and succeeding windows. So there is no need of storing j in the queue and we can discard A[j] forever.

For example, if the current queue has the elements: [4 13 9], and a new element in the window has the element 15. Now, we can empty the queue without considering elements 4, 13, and 9, and insert only element 15 into the queue.

3 代码

    // 暴力解法:采用左右边界滑动窗口
// Time:O(n*k)
public int[] maxSlidingWindow1(int[] nums, int k) {
int len = nums.length;
if (len == 0)
return new int[0];
int left = 0, right = k - 1;
int[] res = new int[len - k + 1];
while (right < len) {
res[left] = nums[left];
for (int i = left + 1; i <= right; i++) {
res[left] = Math.max(res[left], nums[i]);
}
left++;
right++;
}
return res;
} // 用TreeSet实现堆,减少查询最大值的效率,降低了复杂度。
// Wrong Answer:无法解决重复元素的问题。
// Time:O(nlogK) Space:O(k)
public int[] maxSlidingWindow2(int[] nums, int k) {
int len = nums.length;
if (len == 0)
return new int[0];
int[] res = new int[len - k + 1];
TreeSet<Integer> heap = new TreeSet<Integer>();
for (int i = 0; i < k - 1; i++) {
heap.add(nums[i]);
}
for (int i = k - 1; i < len; i++) {
heap.add(nums[i]);
int index = i - k + 1;
res[index] = heap.last();
heap.remove(nums[index]);
}
return res;
} // 用双端队列来解决,时间复杂度降到了O(n)
// Time:O(n) Space:O(k)
public int[] maxSlidingWindow(int[] nums, int k) {
int len = nums.length;
if (len == 0)
return new int[0];
int[] res = new int[len - k + 1];
Deque<Integer> dq = new LinkedList<Integer>();
for (int i = 0; i < len; i++) {
int data = nums[i];
while (!dq.isEmpty() && dq.getLast() < data) {
dq.removeLast();
}
dq.add(data);
if (i < k - 1) {
continue;
}
int index = i - k + 1;
res[index] = dq.getFirst();
if (res[index] == nums[index]) {
dq.removeFirst();
}
}
return res;
}

4 总结

三种方法解决,如何解决堆储存重复元素的问题。

leetcode面试准备:Sliding Window Maximum的更多相关文章

  1. 【LeetCode】239. Sliding Window Maximum

    Sliding Window Maximum   Given an array nums, there is a sliding window of size k which is moving fr ...

  2. 【刷题-LeetCode】239. Sliding Window Maximum

    Sliding Window Maximum Given an array nums, there is a sliding window of size k which is moving from ...

  3. 【LeetCode】239. Sliding Window Maximum 解题报告(Python&C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 单调递减队列 MultiSet 日期 题目地址:ht ...

  4. 【LeetCode 239】Sliding Window Maximum

    Given an array nums, there is a sliding window of size k which is moving from the very left of the a ...

  5. [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 a ...

  6. Leetcode: sliding window maximum

    August 7, 2015 周日玩这个算法, 看到Javascript Array模拟Deque, 非常喜欢, 想用C#数组也模拟; 看有什么新的经历. 试了四五种方法, 花时间研究C# Sorte ...

  7. [LeetCode] 239. Sliding Window Maximum 滑动窗口最大值

    Given an array nums, there is a sliding window of size k which is moving from the very left of the a ...

  8. LeetCode题解-----Sliding Window Maximum

    题目描述: Given an array nums, there is a sliding window of size k which is moving from the very left of ...

  9. [leetcode]239. Sliding Window Maximum滑动窗口最大值

    Given an array nums, there is a sliding window of size k which is moving from the very left of the a ...

随机推荐

  1. Sql Server通过BCP数据导出Excel

    1.1. bcp的主要参数介绍 bcp共有四个动作可以选择. (1) 导入. 这个动作使用in命令完成,后面跟需要导入的文件名. (2) 导出. 这个动作使用out命令完成,后面跟需要导出的文件名. ...

  2. Java_Web _Servlet生命周期实验

    第一次加载这个servlet程序时(选择右边的servlet程序,注意servlet程序没有main函数,因此执行的是run as servlet Application ),同时执行init()方法 ...

  3. 启用Win8(中文版/核心版)中被阉割的远程桌面服务端

    Windows 8/8.1 标准版(中文版/核心版)中取消了远程桌面服务端,想通过远程连接到自己的电脑就很麻烦了,第三方远程桌面速度又不理想(如TeamViewer).通过以下方法可让系统恢复远程桌面 ...

  4. “Assign Random Colors” is not working in 3ds Max 2015

    Go to Customize -> Preferences…-> General (tab) Uncheck “Default to By Layer for New Nodes”

  5. Boot Petalinux Project Using a remote system

    通过jtag实现在远程服务器端下载petalinux image到连接在本地PC的开发板上的方法. 具体连接方式为 比如Host的系统为Windows,Remote system为运载在远程服务器上的 ...

  6. 事件兼容IE

    addEvent:function(target, functionref, tasktype) { if (target.addEventListener) target.addEventListe ...

  7. C# WinForm动态控件实例:口算训练

    昨天晚上回寝室看到室友正在被一个C#课的作业苦恼,作业的内容是编写一个口算训练程序,能够实现随意添加题目数量.于是,喜欢写C#的我就决定解救一下他们. 创建动态控件 既然要动态添加,那就必须使用动态控 ...

  8. php中一些安全性防止问题建议

    只要我们作好了各类操作就可在基本防止一些朋友利用网站本身的漏洞进行网站操作了,很多在php中都有的如XSS用 htmlentities()预防XSS攻击还有sql注入可以用mysql_real_esc ...

  9. 5.MVC框架开发(强类型开发,控制器向界面传递数据的几种方法)

    界面表单中的表单元素名字和数据库表的字段名相一一映射(需要哪个表的数据就是那个表的模型(Model)) 在View页面中可以指定页面从属于哪个模型 注:以上的关系可以通过MVC的强类型视图开发来解决我 ...

  10. 开发设计模式(五)单例模式(Singleton Pattern)

    http://blog.sina.com.cn/s/blog_89d90b7c0101805m.html 单例模式:意思就是只有一个实例.单例模式确保某一个类只有一个实例,而且自行实例化并向整个系统提 ...