leetcode:(274)H-Index(java)
阿新 • • 發佈:2018-11-06
package LeetCode_HashTable; /** * 題目: * Given an array of citations (each citation is a non-negative integer) of a researcher, * write a function to compute the researcher's h-index. * According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her * N papers have at least h citations each, and the other N − h papers have no more than h citations each." * Example: * Input: citations = [3,0,6,1,5] * Output: 3 * [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, her h-index is 3. * (3,0,6,1,5]表示研究人員共有5篇論文,每篇論文分別獲得3次,0次,6次,1次5次引用。由於研究人員有3篇論文,每篇論文至少引用3篇, * 其餘兩個每個引用次數不超過3次,她的h指數為3。) * 題目大意: * 給定研究者的引用陣列(每個引用是非負整數),編寫一個函式來計算研究者的h指數。 * 根據維基百科上h-index的定義:“如果他/她的N篇論文中至少有h引文,那麼科學家就有索引h,其他的N-h論文每篇都不超過引 數。” * 解題思路: * 根據給出的陣列citations建立一個新的陣列array,使新陣列的索引代表論文被引用的次數,陣列值代表引用次數出現的次數。 * 然後從新陣列的末尾開始向陣列的頭部開始遍歷,在每次遍歷時,將陣列值累加求和sum,若出現所求和大於陣列索引, * 則此時的陣列索引即為所求的h指數。 */ public class HIndex_274_1022 { public int HIndex(int[] citations) { if (citations == null || citations.length == 0) { return 0; } int length = citations.length; int[] array = new int[length + 1]; for (int i = 0; i < length; i++) { if (citations[i] >= length) { array[length] += 1; } else array[citations[i]] += 1; } int result ; int num = 0; for (result = length; result >= 0; result--) { num += array[result]; if (num >= result) { return result; } } return 0; } public static void main(String[] args) { int[] array = {3, 0, 6, 1, 5}; HIndex_274_1022 test = new HIndex_274_1022(); int result = test.HIndex(array); System.out.println(result); } }