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. JMeter学习(二十八)内存溢出解决方法(转载)

    转载自 http://www.cnblogs.com/yangxia-test 使用jmeter进行压力测试时遇到一段时间后报内存溢出outfmenmory错误,导致jmeter卡死了,先尝试在jme ...

  2. Android笔记:Button

    示例代码摘自<第一行代码> ButtonDemo.java的代码: public class ButtonDemo extends Activity { @Override protect ...

  3. POJ-3414.Pots.(BFS + 路径打印)

    这道题做了很长时间,一开始上课的时候手写代码,所以想到了很多细节,但是创客手打代码的时候由于疏忽又未将pair赋初值,导致一直输出错误,以后自己写代码可以专心一点,可能会在宿舍图书馆或者Myhome, ...

  4. JS中取得<asp:TextBox中的值

    var s = document.getElementById("<%=txt_DaShen.ClientID %>").value; 注:txt_DaShen 为as ...

  5. 【mybatis基础】mybatis开发dao两种方法

    mybatis是一个支持普通SQL查询,存储过程和高级映射的优秀的持久层的框架,是apache下的顶级项目.mybatis消除了几乎所有的JDBC代码和参数的手工设置以及对结果集的检索封装.mybat ...

  6. 自动化测试之selenium工具简单介绍

    一.selenium简单介绍 1.selenium的成员 2.selenium工作原理 二.webdrive 常见元素定位

  7. C++中的字符数组与字符指针

    //[C++基础]字符数组和字符指针.cpp//剑指offer上的这段话://为了节省内存,c/c++把常量字符串放到单独的一个内存空间.但是当几个指针赋值给相同的常量字符串时,它们实际上会指向相同的 ...

  8. 8.14 git??sourceTree??

    目前这个项目是四个前端在做,我用的版本控制工具是sourceTree,有两个人用的是命令行,厉害.(刚哥说,肯定要会命令行的,(⊙o⊙)好,我学!!) 上周五提交代码时,文件冲突了,而且我给1.3版本 ...

  9. [leetcode]387. First Unique Character in a String第一个不重复字母

    Given a string, find the first non-repeating character in it and return it's index. If it doesn't ex ...

  10. 如何将python中的List转化成dictionary

    问题1:如何将一个list转化成一个dictionary? 问题描述:比如在python中我有一个如下的list,其中奇数位置对应字典的key,偶数位置为相应的value list : ['品牌', ...