题目来源: LeetCode 75 30 天 JavaScript 挑战
2637. 有时间限制的 Promise 对象
思路
fn
和定时器比较执行时间,如果超出限制时间 t
就 reject
代码
ts
type Fn = (...params: any[]) => Promise<any>;
function timeLimit(fn: Fn, t: number): Fn {
return async function(...args) {
return new Promise((resolve, reject) => {
fn(...args).then(resolve, reject)
setTimeout(() => reject("Time Limit Exceeded"), t)
})
}
};
2622. 有时间限制的缓存
思路
用 Map
对象存储数据,给每一项添加时间限制,超时的项目直接删除
代码
ts
interface Record {
time: number,
data: number
}
class TimeLimitedCache {
store: Map<number, Record>
constructor() {
this.store = new Map()
}
set(key: number, value: number, duration: number): boolean {
const now = Date.now()
if (this.store.has(key)) {
const val = this.store.get(key)
val.time = now + duration
val.data = value
this.store.set(key, val)
return true
}
this.store.set(key, {
data: value,
time: now + duration
})
return false
}
get(key: number): number {
if (!this.store.has(key)) {
return -1
}
const val = this.store.get(key)
const now = Date.now()
const time = val.time
if (now > time) {
return -1
}
return val.data
}
count(): number {
const now = Date.now()
let res = 0
for (let item of this.store) {
const [key, val] = item
if (now > val.time) {
this.store.delete(key)
} else {
res++
}
}
return res
}
}
933. 最近的请求次数
思路
每次调用 ping
就向 list
添加这次请求,然后返回数组中小于 t - 3000
的请求数
代码
ts
class RecentCounter {
list: Array<number>
constructor() {
this.list = []
}
ping(t: number): number {
this.list.push(t)
while(this.list[0] < t - 3000) {
this.list.shift()
}
return this.list.length
}
}
649. Dota2 参议院
思路
使用一个队列和一个栈,每次从队列开头拿出一项跟栈最后一项比较,相同就推进栈,不同就把栈顶推出,添加到队列尾
代码
ts
function predictPartyVictory(senate: string): string {
const stack = []
const queue = senate.split("")
while(queue.length) {
const c = queue.shift()
if (stack.length === 0 || stack[stack.length - 1] === c) {
stack.push(c)
} else {
queue.push(stack.pop())
}
}
return stack.pop() === 'R' ? 'Radiant' : 'Dire'
};
本文完,感谢阅读 🌹