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

数组中的最大值 #131

Open
Sunny-117 opened this issue Nov 3, 2022 · 6 comments
Open

数组中的最大值 #131

Sunny-117 opened this issue Nov 3, 2022 · 6 comments

Comments

@Sunny-117
Copy link
Owner

No description provided.

@CXGBro
Copy link

CXGBro commented Dec 24, 2022

// 三种方法
let arr = [5,2,7,9]
// let res = Math.max(...arr)
// let res = arr.sort()[arr.length-1]
let res=arr[0]
for(let i=0;i<arr.length;i++){
  if(arr[i]>res){
    res = arr[i]
  }
}
console.log(res);

@BingGuanqi
Copy link

// 三种方法
let arr = [5,2,7,9]
// let res = Math.max(...arr)
// let res = arr.sort()[arr.length-1]
let res=arr[0]
for(let i=0;i<arr.length;i++){
  if(arr[i]>res){
    res = arr[i]
  }
}
console.log(res);

arr.sort()[arr.length - 1] 这种方法不能得到答案,sort函数需要指定排序函数才行。因为默认的排序函数是会将数组中的数据转化成字符串进行比较的,而字符串大小比较是根据字典序的(如:会出现 "11" < "2" 的情况)
正确写法应该是:
arr.sort(function(a, b) { return a -b })[arr.length-1]

@CXGBro
Copy link

CXGBro commented Jan 12, 2023

// 三种方法
let arr = [5,2,7,9]
// let res = Math.max(...arr)
// let res = arr.sort()[arr.length-1]
let res=arr[0]
for(let i=0;i<arr.length;i++){
  if(arr[i]>res){
    res = arr[i]
  }
}
console.log(res);

arr.sort()[arr.length - 1] 这种方法不能得到答案,sort函数需要指定排序函数才行。因为默认的排序函数是会将数组中的数据转化成字符串进行比较的,而字符串大小比较是根据字典序的(如:会出现 "11" < "2" 的情况) 正确写法应该是: arr.sort(function(a, b) { return a -b })[arr.length-1]

感谢指正

@bearki99
Copy link

const arr = [1, 3, 55, 77, 1000];
// 1. 调用Math
let res = Math.max(...arr);
// 2. 排序
arr.sort((a, b) => a - b)[arr.length - 1];
// 3. 可以采用快排
// 4. 直接获取最大值
function getMax(arr){
    let res = -Infinity;
    for(let i = 0; i < arr.length; i++){
        res = Math.max(res, arr[i]);
    }
    return res;
}

@vivipure
Copy link

vivipure commented Mar 8, 2023

function getMaxInArr(arr) {
  return arr.reduce((acc, cur) => acc > cur ? acc : cur)
}

@MoYuanJun
Copy link

const arr = [5,2,7,9]

// 1. 排序取值
const max1 = arr.sort()[arr.length - 1]

// 2. 使用 Math.max
const max2 = Math.max(...arr)

// 3. 循环取值
const max3 = arr.reduce((t, e) => (t > e ? t : e), 0)

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

6 participants