常见算法
js-查找字符串中出现次数最多的字符
var str = "abcdffffggj"; var obj = {}; for(var i = 0; i < str.length; i++){
//charAt() 方法可返回指定位置的字符。 if(!obj[str.charAt(i)]){ obj[str.charAt(i)] = 1; }else{ obj[str.charAt(i)]++; } } console.log(obj); var max = 0, name = ""; for(var i in obj){ if(obj[i] > max){ max = obj[i]; name = i; } } console.log(name+":"+max);
js找出两个数组中不同的元素
var arr1 = [1,2,3]; var arr2 = [2,3,4,5,6]; let output = arr1 .filter(x => arr2.indexOf(x) == -1) .concat(arr2.filter(x => arr1.indexOf(x) == -1)); console.log(output);
随机生成100个0~100之间的随机数
var arr = []; for(var i = 0; i < 100; i++){ arr[i] = Math.floor(Math.random()*101); } console.log(arr);
排序(冒泡排序)
var sorted = true;
for(var i = 0; i < arr.length; i++){ for(var j = 0; j < arr.length - 1 - i; j++){ if(arr[j] > arr[j+1]) { arr[j] = [arr[j+1],arr[j+1] = arr[j]][0]; sorted=false; } } if(sorted==true){ break; }
}
查找
function search(arr,data){ var max = arr.length-1, //最大值 min = 0; //最小值 while(min<=max){ var mid = Math.floor((max+min)/2); //中间值 if(arr[mid]<data){ min = mid+1; }else if(arr[mid]>data){ max = mid-1; }else{ return mid; } } return -1; //没找到返回-1 }
console.log(arr);//[0, 1, 2, 2, 3, 4, 4, 4, 5, 6, 7, 10, 11, 12, 14, 15, 16, 17, 18, 18, 20, 21, 23, 24, 24, 24, 25, 25, 25, 26, 28, 28, 34, 35, 35, 38, 39, 39, 40, 40, 42, 44, 48, 48, 49, 51, 51, 51, 53, 54, 54, 54, 55, 56, 58, 59, 59, 59, 60, 61, 62, 62, 63, 63, 65, 66, 67, 68, 68, 69, 69, 71, 71, 72, 73, 74, 76, 76, 77, 82, 83, 84, 85, 86, 86, 86, 86, 87, 90, 91, 91, 94, 94, 94, 94, 95, 95, 97, 98, 100]
console.log(search(arr,25)); //27
console.log(search(arr,104)); //-1
查找重复次数(通过向左向右遍历查找重复出现的次数。)
function count(arr,data){ var count = 0; var position = search(arr,data); if(position>-1){ count++; for(var i=position-1;i>0;i--){ if(arr[i]==data){ count++; }else{ break; } } for(var i=position+1;i<arr.length;i++){ if(arr[i]==data){ count++; }else{ break; } } } return count; }