Python暴力通关
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| class Solution(object): def maxSlidingWindow(self, nums, k): """ :type nums: List[int] :type k: int :rtype: List[int] """ ret = [] length = len(nums) if 0 == length: return [] w = length - k + 1 for i in range(w): m = max(nums[i:i+k]) ret.append(m) return ret
|
JavaScript双向队列 时间复杂度O(n)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| var maxSlidingWindow = function(nums, k) { var window = [];
var answer = []; for(var i = 0; i < nums.length; i++) {
if(0 != window.length && window[0] == i - k) window.shift();
while(0 != window.length && nums[window[window.length - 1]] < nums[i]) window.pop();
window.push(i); if(i >= k-1) answer.push(nums[window[0]]); } return answer; };
|
若你觉得我的文章对你有帮助,欢迎点击上方按钮对我打赏