在平时的开发中很少有机会接触到算法,这种不熟悉的神秘感让我更加期待她、迫切希望了解她;对于算法的学习,我希望可以获得不常见的、更有趣的一种思考方式,同时也让自己拥有更多的可能性。


普通思维

我们都知道只有两个数字才可以比大小,所以对于数组比大小就两个两个的比。
思路

  1. 用一个变量记录最大值max_value;
  2. for循环数组内的每一个值,将大的赋值给1的变量(max_value);
  3. 循环结束后,return max_value。

    1. const array = [23,99,17,28,84];
    2. const max = (array) =>{
    3. let max_value = array[0];
    4. for(let i = 1; i < array.length; i+=1) {
    5. const currentNumber = array[i];
    6. if (max_value < currentNumber) max_value = currentNumber;
    7. }
    8. return max_value;
    9. }
    10. console.log(max(array));

    数学思维

    归纳公式

    数学思维要求我们学会总结归纳,我们需要学习将其总结为公式,跟着公式就很容易写代码了。
    从求最大值了解递归 - 图1

    转公式为代码

    “看图写话” ```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. **优化1次**
  2. ```javascript
  3. const max3 = ([first, ...others]) => {
  4. if (others.length === 1) return first > others ? first : others[0];
  5. return first > max2(others) ? first : max2(others);
  6. }
  7. console.log(max3(array));

优化2次【最优版】

  1. const maxOfTwo = (a, b) => a > b ? a : b;
  2. const max4 = ([first, ...others]) =>
  3. others.length === 0 ? first
  4. : maxOfTwo(first, max4(others))
  5. console.log(max4(array));

图解递归

从求最大值了解递归 - 图2
image.png