給你一個整數數組 citations ,其中 citations[i] 表示研究者的第 i 篇論文被引用的次數。計算并返回該研究者的 h 指數。 根據維基百科上 h 指數的定義:h 代表“高引用次數” ,一名科研人員的 h 指數 是指他(她)至少發表了 h 篇論文,并且 至少 有 h 篇論文被引用次數大于等于 h 。如果 h 有多種可能的值,h 指數 是其中最大的那個。
方法一:排序法
思路
首先對引用次數數組進行降序排序,然后從最大的可能?h
?指數(即數組的長度)開始遞減檢查,找到滿足條件(至少有?h
?篇論文被引用次數大于等于?h
)的最大?h
?值。
代碼實現
function hIndex(citations: number[]): number {// 對引用次數數組進行降序排序citations.sort((a, b) => b - a);let h = 0;for (let i = 0; i < citations.length; i++) {if (citations[i] >= i + 1) {h = i + 1;} else {break;}}return h;
}// 示例調用
const citations = [3, 0, 6, 1, 5];
const h = hIndex(citations);
console.log("h 指數為:", h);
復雜度分析
- 時間復雜度:O(n),主要是排序操作的時間開銷,常見排序算法的平均時間復雜度為?,其中??是數組的長度。
- 空間復雜度:O(logn),這是排序算法通常需要的額外空間復雜度。
方法二:計數法
思路
先統計每個引用次數出現的論文數量,同時考慮引用次數大于等于數組長度的情況。然后從數組長度開始遞減檢查,累加滿足條件的論文數量,找到最大的?h
?值。
代碼實現
function hIndex(citations: number[]): number {const n = citations.length;const count = new Array(n + 1).fill(0);// 統計每個引用次數出現的論文數量for (const citation of citations) {if (citation >= n) {count[n]++;} else {count[citation]++;}}let total = 0;// 從 n 開始遞減檢查for (let i = n; i >= 0; i--) {total += count[i];if (total >= i) {return i;}}return 0;
}// 示例調用
const citations2 = [3, 0, 6, 1, 5];
const h2 = hIndex(citations2);
console.log("h 指數為:", h2);
復雜度分析
- 時間復雜度:O(n),只需要遍歷數組兩次,第一次統計引用次數,第二次尋找?
h
?指數,其中??是數組的長度。 - 空間復雜度:O(n),主要用于存儲計數數組。
總結
排序法實現較為直觀,但時間復雜度較高;計數法時間復雜度較低,在處理大規模數據時性能更優。你可以根據實際情況選擇合適的方法。