题目来源于这位大佬的博客:『前端积累』算法汇总【持续更新】 - 风雨后见彩虹 - 博客园 (cnblogs.com)
// 求数组内两数和,跟题目要求不太一样 var nums = [1,2,2,4,3,6,8,5]; var target = 6; var result = []; nums.forEach((item, index) => { const idx = nums.findIndex(e => ((target - item) === e)); if (idx !== -1 && idx !== index && idx >= index) { result.push({ start: index, end: idx }) } }) console.log(result); // 求字符串出现次数最多的字母 const str = 'sfndhvdgndjkfvcvcfwfsdndjfbdhfvdgh'; let max = 0; let maxKey = ''; newStr = str.split('').reduce((item, next) => { item[next] ? item[next] ++ : item[next] = 1; if (item[next] > max) { max = item[next]; maxKey = next; } return item; }, {}) console.log(newStr); console.log(max, maxKey); // 求n位数所有水仙花数 const flower = (num, n) => { let test = num; let sum = 0; for (let i = 1; i <= n; i++) { sum += Math.pow(test % 10, n); test = (test - test % 10) / 10; } return sum === num; } const allFlower = n => { const result = []; const min = Math.pow(10, n-1); const max = Math.pow(10, n) - 1; for (let i = min; i <= max; i++) { if (flower(i, n)) { result.push(i); } } return result; } console.log(allFlower(8)); //8位数需要将近一分钟才能算完,性能问题较差 // 同名去重,不区分大小写 let nameArr = [ 'tao', 'Tao', 'Mom', 'David', 'david', 'Meon', 'mimi' ]; const delSameName = arr => { const names = arr.reduce((item, next) => { next = next.toLowerCase(); typeof item.find(e => (next === e)) === 'undefined' && item.push(next); return item; }, []); console.log(names); } delSameName(nameArr); // 反转数字 let num = -50.2; num = parseFloat(`${num}`.split('').reverse().join('')) * Math.sign(num); // Math.sign()判断正负数,太菜了,这个不懂,参考的大佬代码 console.log(num); // 求第n个斐波那契数 直接求非数组版 const fbnq = n => { if (n === 1) { return 0; } else if (n === 2) { return 1; } let per = 0; let cur = 1; let res = 0; for (let i = 3; i <= n; i++) { res = per + cur; // 交换两数 per += cur; cur = per - cur; per -= cur; // 当前数需相加 cur = cur + per; } return res; } console.log(fbnq(6)); // 求第n个斐波那契数 数组版 const fbnq = n => { let fb = [0, 1]; if (n === 1) { return 0; } else if (n === 2) { return 1; } for (let i = 2; i <= n; i++) { fb.push(fb[i-2] + fb[i-1]); } return fb[n-1]; } console.log(fbnq(6));
// 数组合并排序 let numArr1 = [4,93,23,6,8]; let numArr2 = [3,23,53,1,34]; const newNumArr = numArr1.concat(numArr2).sort((a, b) => a-b); console.log(newNumArr); // 求分解质因数 const zysNum = num => { const res = []; for (let i = 2; i <= num; i++) { if (num % i === 0) { num = num / i; res.push(i); i--; } } return res; } console.log(zysNum(600)); // 可以删除一个字符的回文 aba和abca都是true const isHW = hw => { let isOnly = 1; const newHw = hw.split(''); const fhw = hw.split('').reverse(); for (let index = 0; index < (newHw.length / 2); index++) { if (newHw[index] !== fhw[index]) { // 判断相反位置的两个是否相等 if (isOnly) { // 是第一次不相同,删除反转字串该字符后置0 fhw.splice(index, 1); isOnly = 0; if (newHw[index] !== fhw[index]) { return false; } } else { // 不是第一次不相同,直接返回false return false; } } } return true; } console.log(isHW('abca'));