Open EdwardZZZ opened 6 years ago
接雨水
const arr = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1];
function trap(height) {
const len = height.length;
let [l, r, lMax, rMax, result] = [0, len - 1, 0, 0, 0];
while (l < r) {
const lh = heights[l];
const rh = heights[r];
if (lh < rh) {
if (lh < lMax) {
result += lMax - lh;
} else {
lMax = lh;
}
l++;
} else {
if (rh < rMax) {
result += rMax - rh;
} else {
rMax = rh;
}
r--;
}
console.log(l, r);
}
return result;
};
console.log(trap(arr));
滑动窗口中的最大值
const nums = [1, 3, -1, -3, 5, 3, 6, 7, 3, 3, 2, 2, 1, 1]
function maxSlidingWindow(nums, k) {
const queue = [];
const result = [];
for (let i = 0; i < nums.length; i++) {
// 如果新来的最大,清空队列
if (nums[queue[0]] < nums[i]) queue.length = 0;
// 清除失效
if (queue.length > 0 && queue[0] < i - k + 1) queue.shift();
// 清除中间,只留两头大的
while(nums[queue[queue.length - 1]] < nums[i]) {
queue.pop();
}
queue.push(i);
if (i >= k - 1) result.push(nums[queue[0]]);
}
return result;
}
console.log(maxSlidingWindow(nums, 3));
解绑匿名函数