高级前端
手写代码
【Q629】实现一个函数 max,找到数组中最大的一个值/两个值/N个值

实现一个函数 max,找到数组中最大的一个值/两个值/N个值

Issue 欢迎在 Gtihub Issue 中回答此问题: Issue 647 (opens in a new tab)

Author 回答者: shfshanyue (opens in a new tab)

求最大的一个值:

function max(list) {
  if (!list.length) {
    return 0;
  }
  return list.reduce((x, y) => (x > y ? x : y));
}

求最大的两个值:

代码见 找出数组中最大的两个值 - codepen (opens in a new tab)

function maxTwo(list) {
  let max = -Infinity,
    secondMax = -Infinity;
  for (const x of list) {
    if (x > max) {
      secondMax = max;
      max = x;
    } else if (x > secondMax) {
      secondMax = x;
    }
  }
  return [max, secondMax];
}

如果求 TopN,可使用大顶堆、小顶堆实现,见另一个问题

Author 回答者: Yu-Lxy (opens in a new tab)

const maxTwo = (arr) => {
  const max = Math.max(...arr);
  const secondMax = Math.max(...arr.filter((a) => a !== max));
  return [max, secondMax];
};

Author 回答者: yinsang (opens in a new tab)

若存在相同最大值,此法凉凉~

Author 回答者: Hazel-Lin (opens in a new tab)

const arr = [1, 2, 3, 4, 20, 20];
const arr2 = [0, -1];
const arr3 = [];
 
function findLargestTwoNumbers(arr) {
  if (!arr.length) return;
 
  let max = -Infinity,
    second = -Infinity;
 
  for (let i of arr) {
    console.log(i);
    if (i > max) {
      second = max;
      max = i;
    } else if (i > second) {
      second = i;
    }
  }
  return [max, second];
}
console.log(findLargestTwoNumbers(arr));
console.log(findLargestTwoNumbers(arr2));
console.log(findLargestTwoNumbers(arr3));