Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
wingmeng opened this issue May 12, 2019 · 2 comments
Open

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

wingmeng opened this issue May 12, 2019 · 2 comments

Comments

@wingmeng
Copy link
Collaborator

wingmeng commented May 12, 2019

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

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

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

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

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


本期优秀回答者: @liwenkang

@liwenkang
Copy link

function findMaxMin(arr) {
    return [Math.max(...arr), Math.min(...arr)];
}

@cnyballk
Copy link

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
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants