題目
給定一個整數陣列 citations
,其中 citations[i]
是論文被引用次數,需返回該研究人員的論文 h 指數。
根據維基百科對h指數的定義:h指數被定義為 h
的最大值,使得給定的研究人員至少發表了 h
篇論文,並且每篇論文都被至少被引用 h
次。
Example 1:
Input: citations = [3,0,6,1,5]
Output: 3
Explanation: [3,0,6,1,5] means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively.
Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3.
Example 2:
Input: citations = [1,3,1]
Output: 1
Constraints:
n == citations.length
1 <= n <= 5000
0 <= citations[i] <= 1000
解題思路
- 將論文被引用次數由大到小排序
- 排序完後從前至後遍歷,如果當前論文引用數大於等於已經遍歷個數則h指數加1
完整程式碼
/**
* @param {number[]} citations
* @return {number}
*/
var hIndex = function(citations) {
let h = 0
citations = citations.sort((a, b) => b - a)
for (let i = 0; i < citations.length; i++) {
if (citations[i] > 0 && citations[i] >= i + 1) {
h++
}
}
return h
};