首页 > 代码库 > 239. Sliding Window Maximum

239. Sliding Window Maximum

Python暴力通关

 1 class Solution(object): 2     def maxSlidingWindow(self, nums, k): 3         """ 4         :type nums: List[int] 5         :type k: int 6         :rtype: List[int] 7         """ 8         ret = [] 9         length = len(nums)10         if 0 == length:11             return []12         w = length - k + 113         for i in range(w):14             m = max(nums[i:i+k])15             ret.append(m)16         return ret

JavaScript双向队列 复杂度O(n)

 1 var maxSlidingWindow = function(nums, k) { 2   //构造一个双向队列 3   var window = []; 4  5   var answer = []; 6   for(var i = 0; i < nums.length; i++) { 7  8     //删除窗口外的索引 9     if(0 != window.length && window[0] == i - k)10       window.shift();11 12     //每一次新加入的索引时,窗口中值比这个索引小的索引13     //在接下来的窗口移动中永远不会在起作用14     //也就是暗示,窗口内索引值是有序的15 16     //依次删除窗口内无效的索引17     while(0 != window.length && nums[window[window.length - 1]] < nums[i])18       window.pop();19 20     window.push(i);21     if(i >= k-1)22       answer.push(nums[window[0]]);23   }24   return answer;25 };

 

239. Sliding Window Maximum