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. 免费的在线Web文件管理器:Net2FTP,Pydio,eXtplorer,KodExplorer–功能强大

    https://www.freehao123.com/web-ftp/ 经常有朋友在使用一些没有带文件管理器的空间时,苦于没有办法来解压上传的文件压缩包,而如果不先上传压缩包,直接上传文件夹的话耗费的 ...

  2. JAVA的StringBuffer类(转载整理)____非常重要的一个类,线程安全,不用每次创建一个对象,以及和String的区别

    核心部分转载自:http://www.cnblogs.com/springcsc/archive/2009/12/03/1616330.html StringBuffer类和String一样,也用来代 ...

  3. ###《Effective STL》--Chapter2

    点击查看Evernote原文. #@author: gr #@date: 2014-09-15 #@email: forgerui@gmail.com Chapter2 vector和string T ...

  4. UISearchController的使用。(iOS8+)

    这种方法早就发现了,不过一致没用,今天拿过来用,发现了一些问题. 1.这个东西和表视图结合使用很方便,首先,创建新的工程,将表视图控制器作为工程的根视图,并且添加一个导航(当然,你可以不这样做,但是你 ...

  5. linux shell编程学习笔记(二) --- grep命令

    Linux系统中grep命令是一种强大的文本搜索工具,它能使用正则表达式搜索文本,并把匹 配的行打印出来.grep全称是Global Regular Expression Print,表示全局正则表达 ...

  6. libpcap 主要函数及过程详解

    http://blog.chinaunix.net/uid-21556133-id-120228.html libpcap(Packet Capture Library),即数据包捕获函数库,是Uni ...

  7. A Case for Flash Memory SSD in Enterprise Database Applications

    通过分析固态硬盘的特性对数据库中不同对象,如:表,索引,回滚段,重做日志等的应用进行具体研究,最后将数据库中不同的对象进行区别应用

  8. Cloudcraft: 云架构图形可视化(智能AWS图表)

    Cloudcraft: 云架构图形可视化(智能AWS图表) 2016.09.11 官方网站: https://cloudcraft.co/ Cloudcraft是一个Web应用,用图形表示各种AWS服 ...

  9. MVC文件上传 - 使用jquery异步上传并客户端验证类型和大小

    本篇体验MVC上传文件,从表单上传过渡到jquery异步上传. MVC最基本的上传文件是通过form表单提交方式 □ 前台视图部分 <% using(Html.BeginForm("F ...

  10. HTML5的简介

    前言:作为IOS开发工程师,终会接触到网页前端开发,甚至可能会有 用HTML5开发IOS的app客户端的需求.比如现在上架的app就有比如理财类型的app有的就用HTML开发的,从理财类型的app需求 ...