js实现常见的几种算法(数组去重、字符统计、二分查找等)

1、数组去重:利用对象属性进行筛选

1
2
3
4
5
6
7
8
9
10
11
 function filter(arr){
let obj={};
let newArr=[];
for (let i=0;i<arr.length;i++){
if (!obj[arr[i]]) {
obj[arr[i]]=true;
newArr.push(arr[i]);
}
}
return newArr;
}

利用ES6(set数据类型)快速实现:

1
2
3
4
5
let arr1 =[2,3,12,4,3,1,2]
function filter2(arr){
return Array.from(new Set(arr));
}
console.log(filter2(arr1));// 输出[2, 3, 12, 4, 1]

2、统计字符次数(同样利用对象属性实现)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function staticsis(str){
let obj ={},str1 =str.split(''),length = str1.length,char ='',count=1;
if(length>0){
for(let i=0;i<length;i++){
let val = str1[i];
obj[val] =(obj[val])? ++obj[val]:1;
}
for(var key in obj){
if(obj[key]>=count){
count = obj[key];
char = key;
}
}
}
return char;
}
staticsis('ssasaswwqwsssssss123')//返回's'

3、二分查找:(针对升序列表,不断进行二分,直到找到或者确定无)

1
2
3
4
5
6
7
8
9
10
function searHalf(arr,val){
let length = arr.length,low =0,high=length-1;
while(low<=high){
let mid = Math.floor((high+low)/2);
if(arr[mid]===val){return mid;}
else if(arr[mid]<val){low =mid+1;}
else if(arr[mid]>val){high=mid-1;}
}
return -1;
}

4、不借助第三个变量交换两个变量值(交换律与结合律)

1
2
3
4
5
function swap(a,b){
b = b-a;
a = a+b; //a=a+(b-a)=b;
b = a-b; //b=a-b=b-(b-a)=a
}

5、斐波那契数列(非递归实现)

1
2
3
4
5
6
7
8
9
10
11
12
function fibo(n){
let arr=[];
if(n>0){
arr[0] =0;
if(n==1){return arr;}
arr[1] =1;
for(let i=2;i<n;i++){
arr[i] = arr[i-1]+arr[i-2];
}
}
return arr;
}

6、随机生成字符串

1
2
3
4
5
6
7
function randomStr(n){
let str='abcdefghijkmnopqrstuvwxyz9876543210',newStr='',m =str.length;
for(let i=0;i<n;i++){
newStr+=str.charAt(Math.floor(Math.random()*m))
}
return newStr;
}