【算法】前端
本文目录
二分查找方法
详情
/**
* 二分查找
* @param list - 数组
* @param item - 查找的值
*/
function binary_search(list, item) {
let low = 0
let high = list.length - 1
let mid, guess;
while (low <= high) {
mid = Math.floor((low + high) / 2); // 取中间的索引下标,如果是奇数则向下取整
guess = list[mid]; // 取中间的值
console.log(mid, guess)
if (guess == item) {
return mid // 猜对了
}
if (guess > item) {
high = mid - 1 // 猜大了
} else {
low = mid + 1 // 猜小了
}
}
return '没有元素'
}
// 数组
let arr = Array.from(Array(100), (item, index) => {
return index + 1
})
console.log(binary_search(['a', 'b', 'c', 'd', 'e', 'f'], 'd')) // 3
console.log(binary_search(['a', 'b', 'c', 'd', 'e', 'f'], 'g')) // 没有元素
console.log(binary_search(arr, 9)) // 8
跳台阶
一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)
基础用法
function jumpFloor(n) {
if(n<=0)return 0;
if(n == 1) return 1;
if(n==2) return 2;
return jumpFloor(n-1) + jumpFloor(n-2)
}
console.log(jumpFloor(30)) // 输出 1346269
高效率方法
function jumpFloor2(n) {
var target = 0, number1 = 1, number2 = 2;
if(n<=0)return 0;
if(n == 1) return 1;
if(n==2) return 2;
for(var i=3;i<=n;++i) {
target = number1 + number2;
number1 = number2;
number2 = target;
}
return target;
}
console.log(jumpFloor2(100)) // 输出 573147844013817200000
console.log(jumpFloor2(1000)) // 输出 7.0330367711422765e+208
console.log(jumpFloor2(10000)) // 输出 Infinity
数组去重?
简单方法
var arr=['12','32','89','12','12','78','12','32'];
// 最简单数组去重法
function unique1(array){
var n = []; //一个新的临时数组
for(var i = 0; i < array.length; i++){ //遍历当前数组
if (n.indexOf(array[i]) == -1)
n.push(array[i]);
}
return n;
}
arr=unique1(arr);
高效率方法
// 速度最快, 占空间最多(空间换时间)
function unique2(array){
var n = {}, r = [], type;
for (var i = 0; i < array.length; i++) {
type = typeof array[i];
if (!n[array[i]]) {
n[array[i]] = [type];
r.push(array[i]);
} else if (n[array[i]].indexOf(type) < 0) {
n[array[i]].push(type);
r.push(array[i]);
}
}
return r;
}
//数组下标判断法
function unique3(array){
var n = [array[0]]; //结果数组
for(var i = 1; i < array.length; i++) { //从第二项开始遍历
if (array.indexOf(array[i]) == i)
n.push(array[i]);
}
return n;
}
es6方法
es6方法数组去重
arr=[...new Set(arr)];
es6方法数组去重,第二种方法
function dedupe(array) {
return Array.from(new Set(array)); //Array.from()能把set结构转换为数组
}
Live Notes
读者弹幕
读到这里可以伸个懒腰,再回来继续拆问题。
留言提交后会先进入审核,审核通过后对其他读者公开。