var maxSlidingWindow = function(nums, k) { let q = new MaxPriorityQueue, r = newInt16Array(nums.length - k + 1), i = -1 while (++i < k) q.enqueue(i, nums[i] + 10001) r[0] = q.front().priority - 10001, i-- while (++i < nums.length) { q.enqueue(i, nums[i] + 10001) while (q.front().element <= i - k) q.dequeue() r[i - k + 1] = q.front().priority - 10001 } return r; };
题解三:分块
将数组分成k块
指针j→ 统计每块内从块开头到j最大值 指针i← 统计每块内从块结尾到i最大值 滑动区间[i, i + k - 1]最大值 = 某块结尾到i最大值 与 某块开头到i + k - 1最大值 取大
1 2 3 4 5 6 7 8 9 10
var maxSlidingWindow = function(nums, k) { let n = nums.length, p = newInt16Array(n), s = newInt16Array(n), r = newInt16Array(n - k + 1), i = n, j = -1; while (i--) { p[++j] = j % k ? Math.max(p[j - 1], nums[j]) : nums[j] s[i] = i % k ? Math.max(s[i + 1], nums[i]) : nums[i] } while (i++ < n - k) r[i] = Math.max(s[i], p[i + k - 1]) return r };