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. JDK8中JVM堆内存划分

    一:JVM中内存 JVM中内存通常划分为两个部分,分别为堆内存与栈内存,栈内存主要用运行线程方法 存放本地暂时变量与线程中方法运行时候须要的引用对象地址. JVM全部的对象信息都 存放在堆内存中.相比 ...

  2. hibernate 中,出现了错误 "node to traverse cannot be null!" 如何改正

    这个错误基本上是因为hql语句写错了而造成的, 返回找hql输出一下发现, hql语句中间少了几个空格, 写成了String hql = "from"+className+&quo ...

  3. IronPython 的几个问题

    1.在脚本中使用datagridview.Rows[i].Cells[1].Value并将其转换为string时,遇到int类型 有时可是直接使用.toString()转换为字符 有时必须采用str( ...

  4. cdh 5.13 hadoop 集群IP变更详细步骤

    1.因一些不可抗因素,集群IP变更. 修改CM的数据库IP地址 /etc/cloudera-scm-server/db.p... 2.修改每个主机的hosts列表 3.修改SCM数据库的hosts表中 ...

  5. as3.0 橡皮功能2

    package com{ import flash.display.MovieClip; import flash.display.Bitmap; import flash.display.Bitma ...

  6. chattr 和 lsattr 命令介绍---案例:修改passwd文件

    chattr命令的作用很大,其中一些功能是由Linux内核版本来支持的,如果Linux内核版本低于2.2,那么许多 功能不能实现.同样-D检查压缩文件中的错误的功能,需要2.5.19以上内核才能支持. ...

  7. 取得<asp:TextBox中的值:

     取得<asp:TextBox中的值:  var a= document.getElementById("<%= (ID名).ClientID %>").valu ...

  8. Unity性能优化 – 脚本篇

    https://wuzhiwei.net/unity_script_optimization/

  9. Codeforces Beta Round #42 (Div. 2)

    Codeforces Beta Round #42 (Div. 2) http://codeforces.com/contest/43 A #include<bits/stdc++.h> ...

  10. python中类变量和成员变量、局部变量总结

    class Member(): num= #类变量,可以直接用类调用,或用实例对象调用 def __init__(self,x,y): self.x=x #实例变量(成员变量),需要它是在类的构造函数 ...