← 输入框|github.com|刷新
Skip to content

第 5 期(2019-05-12):数组最大数最小数 #7

Open

Description

@wingmeng

来源:经典算法题
难度:★★

求一个给定数组中的最大数、最小数

/**
 * @param {array} arr - 给定的数组,数组每项为整数
 * @return {array} 返回最大数最小数组成的数组,格式:[max, min]
 */
function findMaxMin(arr) {
  // 你的代码
}

参考答案: 请参阅 @liwenkang 清脆的回答。

另外,如果需要兼容 ES5,可以写成 Math.max.apply(0, arr) Math.min.apply(0, arr)


本期优秀回答者: @liwenkang

Activity

  1. liwenkang commented on May 12, 2019

    @liwenkang
    function findMaxMin(arr) {
        return [Math.max(...arr), Math.min(...arr)];
    }
  2. cnyballk commented on May 12, 2019

    @cnyballk
    const getMaxAndMinArray = (a = []) => {
      const l = a.length;
      if (l === 0) return [];
      if (l == 1) {
        return [a[0], a[0]];
      }
      let i = 0,
        j = l - 1,
        max = -Infinity,
        min = Infinity;
      while (i <= j) {
        if (a[i] < a[j]) {
          max = max > a[j] ? max : a[j];
          min = min < a[i] ? min : a[i];
        } else {
          max = max > a[i] ? max : a[i];
          min = min < a[j] ? min : a[j];
        }
        i++;
        j--;
      }
      return [max, min];
    };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions