shfshanyue / Daily-Question

互联网大厂内推及大厂面经整理,并且每天一道面试题推送。每天五分钟,半年大厂中
https://q.shanyue.tech
4.94k stars 510 forks source link

【Q629】实现一个函数 max,找到数组中最大的一个值/两个值/N个值 #647

Open shfshanyue opened 3 years ago

shfshanyue commented 3 years ago

求最大的一个值:

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

求最大的两个值:

代码见 找出数组中最大的两个值 - codepen

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,可使用大顶堆、小顶堆实现,见另一个问题

Yu-Lxy commented 2 years ago
const maxTwo = (arr) => {
    const max = Math.max(...arr)
    const secondMax = Math.max(...arr.filter(a => a !== max))
    return [max, secondMax]
}
yinsang commented 1 year ago

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

Hazel-Lin commented 1 year ago
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))