簡體   English   中英

如何在整數數組中找到第x個最大元素?

[英]How to find the xth greatest element in an array of integers?

我正在嘗試創建一個函數來查找數組中的第x個最大元素。 如果所有整數都是正整數,則下面的代碼效果很好,但是一旦數組中出現負數,則代碼會混亂。 例如:

用樂趣調用函數時([ - 10,-25,-47,-36,0],1)。 輸出應為0但它給出-47。

如何使此功能適用於正數和負數?

const fun = (x, y) => {
    let sorted = x.sort(function(a, b) {
        return a-b;
    });

    let el = x[y -1];

    console.log(el);    
}

x是整數數組,y是第x個最大元素

要按降序對數字進行排序,您應該使用b - a (第二個元素減去第一個元素)。

這允許您獲取數組中最大的數字,如下所示:

 const greatest = (x, y) => { // After this call, the array `x` will be sorted x.sort(function(a, b) { return b - a; }); let el = x[y - 1]; console.log(el); return el; } // First greatest number among those in the array greatest([1, 3, 5], 1); // excepted: 5 greatest([30, 5, 11], 1); // excepted: 30 greatest([-3, -19, -11], 1); // excepted: -3 greatest([1000000, 999999, -1000000], 1); // excepted: 1000000 greatest([Number.POSITIVE_INFINITY, 0, 10000 * 10000 * 10000], 1); // excepted: Infinity greatest([Number.NEGATIVE_INFINITY, 0, -10000 * 10000 * 10000], 1); // excepted: 0 greatest([Number.NaN, Number.NEGATIVE_INFINITY, Number.POSITIVE_INFINITY], 1); // excepted: NaN 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM