前端对于算法的考察可能相对较少,但是每一个大厂都会有对算法的考察与检测。下面是有一些自己总结的一些大厂考察的算法。
冒泡排序
//冒泡算法,让一个数组从小到大进行排列
function mao(arr){
var len = arr.length
for(var i = 0 ;i<len;i++){
for(var j = i+1 ;j<len;j++){
if(arr[i]>arr[j]){
var temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
}
}
continue;
}
console.log(arr);
}
mao([5,6,4,2,3,2]);
数组去重
function sort(arr){
let obj={};
let newArr=[];
for(let i=0;i<arr.length;i++){
if(!obj[arr[i]]){
obj[arr[i]]=1;
newArr.push(arr[i]);
}
}
return newArr;
}
字符串反转
function reverseString(str){
return str.split('').reverse().join('');
}
console.log(reverseString("hello"))
产生随机数
console.log(random(5))
//从字符串里面选择n个字母
function random(n){
let str='123asdasdasrwer';
let obj='';
var l=str.length;
for(let i=0;i<n;i++){
obj+=str.charAt(Math.floor(Math.random()*l));
}
return obj
}
二分查找
//前提为有序数组
//方法一:非递归
function binarySearch(arr,target){
var high = arr.length-1,
low = 0,
mid;
while(low<=high){
mid = Math.floor((low+high)/2);
if(arr[mid]<target){
low+=1;
}else if (arr[mid]>target){
high-=1;
}else{
return mid;
}
}
return -1;
}
//递归
function binarySearch(arr,target,low=0,high=arr.length-1){
var mid = Math.floor((low+high)/2);
if(low<=high){
if(arr[mid]<target){
return binarySearch(arr,target,mid+1,high);
}else if(arr[mid]>target){
return binarySearch(arr,target,low,high-1);
}else {
return mid;
}
}else{
return -1;
}
}
console.log(binarySearch([0,1,3,5,7,9],3));
获取地址栏的参数值
//获取url里面的的某个参数的值
function getUrlByName(url){
let urls= url.split('?')
if(urls[0]==url){
return " "
}
let obj = {};
let arr = urls[1].split('&')
for(let i=0;i<arr.length;i++){
let arg = arr[i].split("=");
obj[arg[0]] =arg[1]
}
return obj;
}
var href = getUrlByName("https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&rsv_idx=2&ch=&tn=baiduhome_pg&bar=&wd=%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BEjs%E5%AE%9E%E7%8E%B0&oq=%25E4%25BA%258C%25E5%2588%2586%25E6%259F%25A5%25E6%2589%25BE&rsv_pq=91ad2676001a9563&rsv_t=dea8C%2F0NYMNPabm3q3HWnJBqwfp8k4iuQvmy3wsxSBA8y%2FVz4nxv4orId%2B5rLjMUThgZ&rqlang=cn&rsv_enter=1&rsv_dl=tb&inputT=1896")
console.log(href['ie'])//utf-8
统计字符串中出现最多的那个字母
function findMaxCharacter(str){
if(str.length==1){
return str;
}
let charobj ={}
for(let i=0; i<str.length;i++){
if(!charobj[str.charAt(i)]){
charobj[str.charAt(i)]=1;
}else{
charobj[str.charAt(i)]+=1
}
}
//找出数组中最大的一个数的
let maxChar =""
let maxValue =1;
for(var k in charobj){
if(charobj[k]>=maxValue){
maxChar = k;
maxValue = charobj[k];
}
}
return maxChar;
}
console.log(findMaxCharacter("shdiadjsaiijdia"));
二叉树的插入
手写快排(复杂度)
分治算法
一行代码实现判断回文字符串
堆排序