Leetcode: Sliding Window Maximum

原创 2015年11月19日 16:04:09

Question

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.

Follow up:
Could you solve it in linear time?

Show Hint
Hide Company Tags Zenefits
Hide Tags Heap
Hide Similar Problems (H) Minimum Window Substring (E) Min Stack (H) Longest Substring with At Most Two Distinct Characters (H) Paint House II
Have you met this question in a real interview? Yes No
Discuss


Analysis

The naive way is to maintain a sliding window with size k. For each window, we sort it and get the max value. the time complexity is O( n * nlog(n) )

It is easy to use heap to get the maximum value. But we need to store both its value and its position. The time complexity is O( n* log(n) ).

The efficient solution takes O( n ).
Actually, if using heap, the most of elems in the bottom of heap are never be used. Think about it. Even if the toppest elem is popped, the second largest elem will be appear. The heap size is always k, some elems in the bottom are discarded.

So we use one queue. Instead of storing all elems in current sliding window, it only stores the potential large elems, decreasing subsequence. It is the same as the function of heap.

The first elem of queue is the largest one for current window. When window slides, we need to pop the first elem and add the new one.


Solution

Get idea from here1, here2

time complexity: O(n)
space complexity: O(k)

process

ind:0,  queue: [1],  ans=[]
1  3  -1 -3  5  3  6  7       

ind:1,  queue: [3],  ans=[]
1  3  -1 -3  5  3  6  7    

ind:2,  queue: [3,-1], ans=[3]
1  3  -1 -3  5  3  6  7    

ind:3,  queue: [3,-1,-3], ans=[3,3]
1  3  -1 -3  5  3  6  7 

ind:4,  queue: [5], ans=[3,3,5]
1  3  -1 -3  5  3  6  7 

ind:5,  queue: [5,3], ans=[3,3,5,5]
1  3  -1 -3  5  3  6  7 

ind:6,  queue: [6], ans=[3,3,5,5,6]
1  3  -1 -3  5  3  6  7 

ind:7,  queue: [7], ans=[3,3,5,5,6,7]
1  3  -1 -3  5  3  6  7 

Code

class Solution(object):
    def maxSlidingWindow(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """

        res, queue = [], []

        for ind in range(len(nums)):
            # make sure the size fo range of all elems in queue is smaller than k  
            if len(queue)>0 and ind-queue[0][0]>=k:
                del queue[0]

            # we don't need to consider the small elem, which are never be the largest one in the range
            while len(queue)>0 and nums[ind] > queue[-1][1]:
                queue.pop()

            queue.append( (ind, nums[ind]) )

            # for each window, output its result
            if ind>=k-1:
                res.append( queue[0][1] )

        return res



版权声明:本文为博主原创文章,未经博主允许不得转载。 举报

相关文章推荐

[LeetCode]Sliding Window Maximum

题目链接:http://leetcode.com/2011/01/sliding-window-maximum.html 咳咳,很长时间没有写博客了。各种各样的事情,前段时间又被各种打击。调整了好久,...

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

精选:深入理解 Docker 内部原理及网络配置

网络绝对是任何系统的核心,对于容器而言也是如此。Docker 作为目前最火的轻量级容器技术,有很多令人称道的功能,如 Docker 的镜像管理。然而,Docker的网络一直以来都比较薄弱,所以我们有必要深入了解Docker的网络知识,以满足更高的网络需求。

LeetCode Sliding Window Maximum

Description: Given an array nums, there is a sliding window of size k which is moving from the ver...

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

LeetCode Sliding Window Maximum

Sliding Window Maximum题目DescriptionGiven an array nums, there is a sliding window of size k which is...

LeetCode|Sliding Window Maximum

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

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

leetcode 239:Sliding Window Maximum

使用linkedList快速地获得一定窗口中的最大元素

Leetcode 239 Sliding Window Maximum

1. 问题描述  给定一个整数数组和一个大小为k的滑动窗口,滑动窗口每次从左到右移动一个数字,返回每次滑动窗口中的最大值。   2. 方法与思路  Method 1:最朴素的解法就是将窗口在数组上进...

【LeetCode-239】Sliding Window Maximum

这道题真的把我打败了,最终还是看的别人的!牛人 /** * 双向队列 * 我们用双向队列可以在O(N)时间内解决这题。 * 当我们遇到新的数时,将新的数和双向队列的末尾比较,如果末尾比新数小,...
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)