20.有效的括号
var isValid = function (s) {
const stack = [];
for (i = 0; i < s.length; i++) {
let c = s[i];
switch (c) {
case '(':
stack.push(')');
break;
case '[':
stack.push(']');
break;
case '{':
stack.push('}');
break;
default:
if (c !== stack.pop())
return false
}
}
return stack.length === 0
};
1047. 删除字符串中的所有相邻重复项
/**
* @param {string} s
* @return {string}
*/
var removeDuplicates = function (s) {
const stack = [];
stack.push(s[0]);
for (i = 1; i < s.length; i++) {
if (s[i] === stack[stack.length - 1]) {
stack.pop();
} else {
stack.push(s[i]);
}
}
return stack.join('');
};
150.逆波兰表达式求值
/**
* @param {string[]} tokens
* @return {number}
*/
var evalRPN = function (tokens) {
const stack = [];
for (i = 0; i < tokens.length; i++) {
if (!isNaN(Number(tokens[i]))) {
stack.push(Number(tokens[i]));
} else {
let c = tokens[i];
let a = stack.pop();
let b = stack.pop();
switch (c) {
case '+':
stack.push(a + b);
break;
case '-':
stack.push(b - a);
break;
case '*':
stack.push(a * b);
break;
case '/':
stack.push(parseInt(b / a));
break;
}
}
}
return stack[0]
};
239.滑动窗口最大值
/**
* @param {number[]} nums
* @param {number} k
* @return {number[]}
*/
var maxSlidingWindow = function (nums, k) {
const ans = []; // 记录最大值的结果
const stack = []; // 维护一个单调递减的单调栈
for (let index = 0; index < nums.length; index ++) {
while (stack.length && nums[stack[stack.length - 1]] <= nums[index]) {
stack.pop()
}
stack.push(index)
if (index - stack[0] >= k) {
stack.shift()
}
if (index >= k - 1) {
ans.push(nums[stack[0]])
}
}
return ans
347.前k个高频元素
用到了优先队列的库,PriorityQueue。
var topKFrequent = function (nums, k) {
const map = new Map();
const res = [];
//使用 map 统计元素出现频率
for (const num of nums) {
map.set(num, (map.get(num) || 0) + 1);
}
//创建小顶堆
const heap = new PriorityQueue({
compare: (a, b) => a.value - b.value
})
for (const [key, value] of map) {
heap.enqueue({ key, value });
if (heap.size() > k) heap.dequeue();
}
//处理输出
while (heap.size()) res.push(heap.dequeue().key);
return res;
};
也可以手写实现优先队列,以下是笔记部分:
// js 没有堆 需要自己构造
class Heap {
constructor(compareFn) {
this.compareFn = compareFn;
this.queue = [];
}
// 添加
push(item) {
// 推入元素
this.queue.push(item);
// 上浮
let index = this.size() - 1; // 记录推入元素下标
let parent = Math.floor((index - 1) / 2); // 记录父节点下标
while (parent >= 0 && this.compare(parent, index) > 0) { // 注意compare参数顺序
[this.queue[index], this.queue[parent]] = [this.queue[parent], this.queue[index]];
// 更新下标
index = parent;
parent = Math.floor((index - 1) / 2);
}
}
// 获取堆顶元素并移除
pop() {
// 堆顶元素
const out = this.queue[0];
// 移除堆顶元素 填入最后一个元素
this.queue[0] = this.queue.pop();
// 下沉
let index = 0; // 记录下沉元素下标
let left = 1; // left 是左子节点下标 left + 1 则是右子节点下标
let searchChild = this.compare(left, left + 1) > 0 ? left + 1 : left;
while (searchChild !== undefined && this.compare(index, searchChild) > 0) { // 注意compare参数顺序
[this.queue[index], this.queue[searchChild]] = [this.queue[searchChild], this.queue[index]];
// 更新下标
index = searchChild;
left = 2 * index + 1;
searchChild = this.compare(left, left + 1) > 0 ? left + 1 : left;
}
return out;
}
size() {
return this.queue.length;
}
// 使用传入的 compareFn 比较两个位置的元素
compare(index1, index2) {
// 处理下标越界问题
if (this.queue[index1] === undefined) return 1;
if (this.queue[index2] === undefined) return -1;
return this.compareFn(this.queue[index1], this.queue[index2]);
}
}
const topKFrequent = function (nums, k) {
const map = new Map();
for (const num of nums) {
map.set(num, (map.get(num) || 0) + 1);
}
// 创建小顶堆
const heap= new Heap((a, b) => a[1] - b[1]);
// entry 是一个长度为2的数组,0位置存储key,1位置存储value
for (const entry of map.entries()) {
heap.push(entry);
if (heap.size() > k) {
heap.pop();
}
}
// return heap.queue.map(e => e[0]);
const res = [];
for (let i = heap.size() - 1; i >= 0; i--) {
res[i] = heap.pop()[0];
}
return res;
};
2558.从数量最多的堆中取走礼物
/**
* @param {number[]} gifts
* @param {number} k
* @return {number}
*/
var pickGifts = function(gifts, k) {
const pq = new MaxPriorityQueue();
gifts.map(v => {
pq.enqueue(v);
});
while (k > 0) {
let x = pq.dequeue().element;
pq.enqueue(Math.floor(Math.sqrt(x)));
k--;
}
let res = 0;
while (pq.size() > 0) {
res += pq.dequeue().element;
}
return res;
};