0217掘金他人的面试题
2025年5月1日大约 3 分钟约 858 字
一个校招小伙子的大厂面试题,自己尝试解决他们的问题,回顾之前自己面试的失败大多数的原因是算法题没过,所以自己主要要去熟悉他们的算法题和输入输出的部分:
详细说一下业务背景、遇到过什么问题以及怎么解决的。
用背景、任务、行动、结果去描述问题;复盘当前项目的难点、解决方案、引申思考
2.输入输出:
for(var i= 0;i< 3; i++){
setTimeout(function(){
console.log('timeout' + i);
})
}
new Promise(function(resolve){
console.log('promise' +i);
for(vari= 0;i< 1000;i++){
i== 99 &&resolve();
}
console.log('promise'+ i});
}).then(function() {
console.log('then' + i);
})
console.log('global'+ i);分析:
调用 resolve 后,Promise 内部的代码会继续执行,但 Promise 本身的状态已经改变。
promise3
promise1000
global1000
then1000
timeout3
timeout3
timeout3手写debounce(用TS写)
防抖:多次点击只响应最后一次。适用于:按钮、批量网络请求、输入
节流:一段时间内只响应一次。适用于:滚动
function debounce<T extends (...args: any[]) => void>(fn: T, wait: number): (...args: Paramaters<T>) => void { let timeout: NodeJs.timeout | null = null return function(...args, ) { timeout && clearTimeout(timeout) timeout = setTimeout(() => { fn.apply(this, args) }, wait) } }function debounce(fn, delay){ let timer = null return function(...args) { timer && clearTimeout(timer) timer = setTimeour(()=>{ fn.apply(this, args) }, timer) } }如果想要第一次进来就执行一下而不是想等定时器计时完再执行怎么做(当时利用闭包的特性利用一个标志位延长变量生命周期实现的);
加一个参数就可以
if (immediate && !timeout) { fn.apply(context, args); // 立即执行函数 }function debounce<T extends (...args: any[]) => void>( fn: T, wait: number, immediate: boolean = false // 添加一个参数来决定是否立即执行 ): (...args: Parameters<T>) => void { let timeout: NodeJS.Timeout | null = null; return function(...args: Parameters<T>) { const context = this; // 如果是立即执行,并且没有定时器在计时 if (immediate && !timeout) { fn.apply(context, args); // 立即执行函数 } // 清除之前的定时器 if (timeout) { clearTimeout(timeout); } // 设置新的定时器 timeout = setTimeout(() => { if (!immediate) { // 如果不是立即执行 fn.apply(context, args); // 在等待时间后执行函数 } timeout = null; // 重置定时器 }, wait); }; }还有就是 throttle,TS实现:
节流是一段时间内无论发生多少次都只执行一次,通常用于滚动、会立即执行
使用场景:窗口变更、scroll、鼠标移动。
function throttle(fn, limit) { let timer = null let lastCall = null retruen function (...args) => { let now = Date.now() let ctx = this if(lastCall || now - lastcall >=limit) { fn.apply(ctx, args) lastcall = Date.now() } else{ timer && clearTimeout(timer) timer = setTimeout(() => { fn.apply(ctx, args) }, limit - (now - (lastCall | 0))) } } }追问了两种各自的局限性,还有就是写出来两者的结合版(当时 有亿点卡住了,在提示下终于写出来了...)
3算法题:括号匹配(要求使用TS),leetcode 的简单题,利用 map 结合一个数组作为栈即可
题目:
给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
每个右括号都有一个对应的相同类型的左括号。
示例 1:
输入:s = "()"
输出:true
示例 2:
输入:s = "()[]{}"
输出:true
示例 3:
输入:s = "(]"
输出:false
示例 4:
输入:s = "([])"
输出:true
提示:
1 <= s.length <= 104
s 仅由括号 '()[]{}' 组成