在平时的开发中很少有机会接触到算法,这种不熟悉的神秘感让我更加期待她、迫切希望了解她;对于算法的学习,我希望可以获得不常见的、更有趣的一种思考方式,同时也让自己拥有更多的可能性。
普通思维
我们都知道只有两个数字才可以比大小,所以对于数组比大小就两个两个的比。
思路:
- 用一个变量记录最大值max_value;
- for循环数组内的每一个值,将大的赋值给1的变量(max_value);
循环结束后,return max_value。
const array = [23,99,17,28,84];const max = (array) =>{let max_value = array[0];for(let i = 1; i < array.length; i+=1) {const currentNumber = array[i];if (max_value < currentNumber) max_value = currentNumber;}return max_value;}console.log(max(array));
数学思维
归纳公式
数学思维要求我们学会总结归纳,我们需要学习将其总结为公式,跟着公式就很容易写代码了。
转公式为代码
“看图写话” ```javascript const max2 = ([…args]) => { if (args.length === 1) return args[0];
return args[0] > max2(args.slice(1)) ? args[0] : max2(args.slice(1)); }
console.log(max2(array));
**优化1次**```javascriptconst max3 = ([first, ...others]) => {if (others.length === 1) return first > others ? first : others[0];return first > max2(others) ? first : max2(others);}console.log(max3(array));
优化2次【最优版】
const maxOfTwo = (a, b) => a > b ? a : b;const max4 = ([first, ...others]) =>others.length === 0 ? first: maxOfTwo(first, max4(others))console.log(max4(array));
图解递归

