Created
August 16, 2015 12:09
-
-
Save junjiah/a695c854314612f3c1c3 to your computer and use it in GitHub Desktop.
solved 'Sliding Window Maximum' on LeetCode https://leetcode.com/problems/sliding-window-maximum/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Maintain a deque where the first element is the max | |
# of the window. | |
class Solution: | |
# @param {integer[]} nums | |
# @param {integer} k | |
# @return {integer[]} | |
def maxSlidingWindow(self, nums, k): | |
results = [] | |
# Element in the window should be (index, val). | |
window = collections.deque() | |
for i, ele in enumerate(nums): | |
# Remove out-of-bound element. | |
if window and i - window[0][0] >= k: | |
window.popleft() | |
# Squeeze the window. | |
while window and window[-1][1] <= ele: | |
window.pop() | |
window.append((i, ele)) | |
# Record the max in the window. | |
if i >= k - 1: | |
results.append(window[0][1]) | |
return results |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment