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. Java:类加载机制及反射

    一.Java类加载机制 1.概述 Class文件由类装载器装载后,在JVM中将形成一份描述Class结构的元信息对象,通过该元信息对象可以获知Class的结构信息:如构造函数,属性和方法等,Java允 ...

  2. GraphicsTier

    [GraphicsTier] 1.enum GraphicsTier 2.enum ShaderQuality 3.enum BuildTargetGroup 4.EditorGraphicsSett ...

  3. SpringBoot点滴(1)

    spring boot 注意事项 1.项目启动的主类,放置位置在所有类的外层与controller,dao,service,util,entity同层,SpringBoot会自动扫描@SpringBo ...

  4. metasploit framework(十四):弱点扫描

    vnc 密码破解 vnc 端口5900 先开启数据库 启动msf vnc无密码访问 RDP远程桌面漏洞 win7 192.168.1.123 xp     192.168.1.122 发现有两个模块, ...

  5. ASP.NET 在请求中检测到包含潜在危险的数据,因为它可能包括 HTML 标记或脚本

    <textarea><%=Server.HtmlEncode(strContent)%></textarea> 转载:https://www.cnblogs.com ...

  6. php拓展

    https://github.com/phalcon/zephirhttp://blog.csdn.net/black_OX/article/details/43700707

  7. 全国高校绿色计算大赛 预赛第一阶段(C++)第3关:旋转数组

    挑战任务 在计算机中,一张数字图像,可以被看做是一个矩阵或者说数组. 学过线性代数的同学对矩阵肯定不陌生.一般来说,图像是一个标准的矩形,有着宽度(width)和高度(height).而矩阵有着行(r ...

  8. TOJ 3850: String Function Encoding

    传送门:http://acm.tzc.edu.cn/acmhome/problemdetail.do?&method=showdetail&id=3850 时间限制(普通/Java): ...

  9. 网页请求get方式

    方法都是博客中的大神写的,谢谢各路大神. 方法一:(亲测有效) //Get请求方式 private string RequestGet(string Url) { string PageStr = s ...

  10. vue 登录前做校验this.$router.push(location)

    有很多按钮在执行跳转之前,还会执行一系列方法,这时可以使用 this.$router.push(location) 来修改 url,完成跳转 例如:登录按钮,点击时需要先判断验证码等是否正确,此时