zoukankan      html  css  js  c++  java
  • 如何确定一个数组中的最大值

    今天面试的一道题目是这样的,假设有一个数组,求出数组中的最大值,我使用的方法是:

     1 var a = [3, 10, 5, 8, 12, 15];
     2 
     3 function compare(value1, value2) {
     4     if (value1 > value2) {
     5         return -1;
     6     } else if (value1 < value2) {
     7         return 1;
     8     } else {
     9         return 0;
    10     }
    11 }
    12 a.sort(compare);
    13 console.log(a[0]);

    后面一想,可以这样精简代码:

    1 var a = [3, 10, 5, 8, 12, 12, 15];
    2 
    3 function compare(value1, value2) {
    4     return value2 - value1; //此时是降序        //value1 - value2 是升序
    5 }
    6 a.sort(compare);
    7 console.log(a[0]);

    今天看书看到Math对象里面,看到了一种以最快的方式求出这个数组中的最大值

    1 var a = [3, 10, 5, 8, 12, 12, 15];

    2 var max = Math.max.apply(Math,a); //注意把第一个参数设置成为Math

    3 console.log(max); 

    如此以来的话就方便很多了。而且通过Math对象提供的计算功能执行起来是最快的。

  • 相关阅读:
    动态表格
    Palindrome Number
    String to Integer (atoi) ???
    Reverse Integer
    Two Sum
    Path Sum
    Minimum Depth of Binary Tree
    Plus One
    Maximum Depth of Binary Tree
    Symmetric Tree
  • 原文地址:https://www.cnblogs.com/qianduanjingying/p/4769543.html
Copyright © 2011-2022 走看看