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. Return the max sliding window.

Example:

Input: nums = [1,3,-1,-3,5,3,6,7], and k = 3
Output: [3,3,5,5,6,7]
Explanation:

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

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

Follow up:
Could you solve it in linear time?

Idea 1. Sliding window, borrow the idea of montone increasing queue, moving two pointers.
右边界向右边滑,扫新的元素, 
  • pop out all nums[j] if nums[right] > nums[j] (j < i), 因为新的数大,窗口中前面的小数不可能是窗口的max value, 形成一个递减的queue, the queue head is the local maximum in the current window;
  • push nums[right]
左边界向右边滑,
        pop out nums[left] if deque.peekFirst == nums[left], 如果左边界是最大值,向右移左边届已经不在有效窗口内,需要从queue头移除最大值
Since pop operation needed on both ending, deque is a suitable struct.
Time complexity: O(n) since each element is only pushed once and poped out once from the deque.
Space complexity: O(n)
1.a deque store the array item
 class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
if(nums.length == 0 || k > nums.length) {
return new int[0];
} Deque<Integer> maxBuffer = new LinkedList<>();
int[] result = new int[nums.length - k + 1]; for(int left = 0, right = 0; right < nums.length; ++right) {
while(!maxBuffer.isEmpty() && nums[right] > maxBuffer.peekLast()) {
maxBuffer.pollLast();
}
maxBuffer.offerLast(nums[right]);
if(right >= k-1) {
result[left] = maxBuffer.peekFirst();
if(nums[left] == result[left]) {
maxBuffer.pollFirst();
}
++left;
}
} return result;
}
}

python

 class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
maxBuffer = collections.deque() result = []
for right in range(len(nums)):
while maxBuffer and maxBuffer[-1] < nums[right]:
maxBuffer.pop() maxBuffer.append(nums[right])
if right >= k - 1:
result.append(maxBuffer[0]) if maxBuffer[0] == nums[right - k + 1]:
maxBuffer.popleft() return result

1.b deque store the array index, instead,

 class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
if(nums.length == 0 || k > nums.length) {
return new int[0];
} int[] result = new int[nums.length - k + 1];
Deque<Integer> maxIndexBuffer = new ArrayDeque();
for(int left = 0, right = 0; right < nums.length; ++right) {
while(!maxIndexBuffer.isEmpty() && nums[maxIndexBuffer.peekLast()] < nums[right] ) {
maxIndexBuffer.pollLast();
}
maxIndexBuffer.offerLast(right); if(right >= k-1) {
int maxIndex = maxIndexBuffer.peekFirst();
result[left] = nums[maxIndex]; if(maxIndex == left) {
maxIndexBuffer.pollFirst();
}
++left;
}
} return result;
}
}

python

 class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
maxIndex = collections.deque() result = []
for right in range(len(nums)):
while maxIndex and nums[maxIndex[-1]] < nums[right]:
maxIndex.pop() maxIndex.append(right)
if right >= k - 1:
result.append(nums[maxIndex[0]]) if maxIndex[0] == right - k + 1:
maxIndex.popleft() return result

Sliding Window Maximum LT239的更多相关文章

  1. leetcode面试准备:Sliding Window Maximum

    leetcode面试准备:Sliding Window Maximum 1 题目 Given an array nums, there is a sliding window of size k wh ...

  2. 【LeetCode】239. Sliding Window Maximum

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

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

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

  4. Sliding Window Maximum 解答

    Question Given an array of n integer with duplicate number, and a moving window(size k), move the wi ...

  5. Sliding Window Maximum

    (http://leetcode.com/2011/01/sliding-window-maximum.html) A long array A[] is given to you. There is ...

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

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

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

  8. Leetcode: sliding window maximum

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

  9. 239. Sliding Window Maximum *HARD* -- 滑动窗口的最大值

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

随机推荐

  1. php支付宝接口 的使用

    下载地址(java/php都有) https://doc.open.alipay.com/doc2/detail?treeId=66&articleId=103571&docType= ...

  2. OnContextMenu实现禁止鼠标右键

    OnContextMenu事件 定义和使用:oncontextmenu 事件在元素中用户右击鼠标时触发并打开上下文菜单.注意:所有浏览器都支持 oncontextmenu 事件, contextmen ...

  3. SQL Server子查询填充DataSet时报500内部错误的解决办法

    运行环境为Visual Studio 2010,数据库为SQL Server 2008. 执行下面SQL语句 SELECT SubsiteId, SubsiteTitle, count(Collect ...

  4. vi 基本命令使用

    vi编辑器是所有Unix及Linux系统下标准的编辑器,它的强大不逊色于任何最新的文本编辑器,这里只是简单地介绍一下它的用法和一小部分指令.由于对 Unix及Linux系统的任何版本,vi编辑器是完全 ...

  5. oracle中取得当前日期,前一天,当前月,前一个月

    当前日:select TRUNC(SYSDATE)  from dual; 前一天: select TRUNC(SYSDATE - 1)   from dual; 前一天转换为日期格式: select ...

  6. iOS开发时使用的bundle路径

    bundle是一个目录,其中包含了程序会使用到的资源. 这些资源包含了如图像,声音,编译好的代码,nib文件(用户也会把bundle称为plug-in). 对应bundle,cocoa提供了类NSBu ...

  7. Qt: 加入打印支持

    写记事本打印功能所遇问题,记录以便于查阅. 在vs系统中开发Qt,加入打印支持,不似在QtCreator之pro文件中中加QT +=printsupport解决. 而要在vs(以vs2015为例)中, ...

  8. 大数据分析界的“神兽”Apache Kylin有多牛?【转】

    本文作者:李栋,来自Kyligence公司,也是Apache Kylin Committer & PMC member,在加入Kyligence之前曾就职于eBay.微软. 1.Apache ...

  9. windows下忘记mysql超级管理员root密码的解决办法(也适用于wamp)

    1.停止mysql服务. 2,在CMD命令行窗口,进入MYSQL安装目录 比如 d:mysql20080505in 3,进入mysql安全模式,即当mysql起来后,不用输入密码就能进入数据库.命令为 ...

  10. 自动化运维工具 SaltStack 搭建

    原文地址:https://www.ibm.com/developerworks/cn/opensource/os-devops-saltstack-in-cloud/index.html#N10072 ...