常见算法
写一个 mySetInterVal(fn, a, b),每次间隔 a,a+b,a+2b,…,a+nb 的时间,然后写一个 myClear,停止上面的 mySetInterVal
function MySetInterVal(fn:Function,a:number,b:number){
this.a=a;
this.b=b;
this.time=0;
this.timer=-1;
this.start=()=>{
this.timer=setTimeout(()=>{
fn();
this.time++;
this.start();
},this.a+this.b*this.time);
}
this.myClear=()=>{
clearTimeout(this.timer);
this.time=0;
}
}
合并二维有序数组成一维有序数组
const mergeTwoSortArr=(arr1:number[],arr2:number[])=>{
let res=[];
// 数组有序,其中一个数组取完了,另一个数组剩下的部分,一定是最大的
while(arr1.length>0&&arr2.length>0){
if(arr1[0]>arr2[0]){
res.push(arr2.shift())
}else{
res.push(arr1.shift());
}
}
return res.concat(arr1).concat(arr2);
}
斐波那契数列
function fib(n) {
if(n < 0) throw new Error('输入的数字不能小于0');
if (n < 2) {
return n;
}
return fib(n - 1) + fib(n - 2);
}
不含重复字符的最长子字符串
function lengthOfLongestSubstring(s: string): number {
let max=0;
let map:string[]=[];
let i=0;
let start=0;
while(i<s.length){
if(map.includes(s[i])){
max=Math.max(max,map.length);
start+=1;
map=[];
i=start;
}else{
map.push(s[i]);
i++;
}
}
return max;
};
循环打印红黄绿
const Red=async ()=>{
console.log('qy:red-----',);
}
const green=()=>{
console.log('qy:green-----',);
}
const yellow=()=>{
console.log('qy:yellow-----',);
}
const documentTraffic=async ()=>{
await Red();
await green();
await yellow();
documentTraffic();
}
documentTraffic();
查找文章中出现频率最高的单词
function findMostWord(s:String) {
// 合法性判断
if(!s) return 'error';
let map:any={};
for(let i =0;i<s.length;i++){
if(!map[s[i]]){
map[s[i]]=1;
}else{
map[s[i]]=map[s[i]]+1;
}
}
const arr=Object.entries(map);
const res= arr.sort(([preK,preV]:any[],[nextK,nextV]:any[])=>{
return preV-nextV;
})
return res[res.length-1].join(',');
}
设计一个方法,找出任意指定单词在一本书中的出现频率
class WordsFrequency {
private map:any= new Map();
constructor(book: string[]) {
book.forEach((item:string)=>{
if(!this.map[item]){
this.map[item]=1;
}else{
this.map[item]=this.map[item]+1;
}
})
}
get(word: string): number {
const get=this.map[word];
if(!get) return 0;
return get;
}
}
const wordsFrequency = new WordsFrequency(["i", "have", "an", "apple", "he", "have", "a", "pen"]);
console.log('qy:-----',wordsFrequency.get("you")); //返回0,"you"没有出现过
console.log('qy:-----',wordsFrequency.get("have")); //返回2,"have"出现2次
console.log('qy:-----',wordsFrequency.get("an")); //返回1
console.log('qy:-----',wordsFrequency.get("apple")); //返回1
console.log('qy:-----',wordsFrequency.get("pen")); //返回1
数组去重
const a=new Set([1,1,3,3,2,2]);
const b=Array.from(a);
爬楼梯
假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
**注意:**给定 n 是一个正整数。
function climbStairs(n: number): number {
let db=[];
db[0]=1;db[1]=1;
for(let i=2;i<=n;i++){
db[i]=db[i-1]+db[i-2];
}
return db[n];
};