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 hof 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 Explanation:[3,0,6,1,5] means the researcher has5 papers in total and each of them had received3, 0, 6, 1, 5 citations respectively. Since the researcher has3 papers with at least3 citations each and the remaining two with no more than3 citations each, her h-index is3 .
Note: If there are several possible values for h, the maximum one is taken as the h-index.
<Solution>
想法如下:
- 將 citation 做分類,分裝到不同的 bucket
- 為什麼選擇用 bucket 的方式分類,因為這邊只在乎在某個數以上的paper數量,和以下的 paper 數量,所以利用 bucket 分類,可以很快計算出以上和以下的數量
- 因為 paper 的數量,剛好等於 array 的長度,所以 bucket 的數量,設為 citations.length + 1,把比 paper 數量多的 citation 都放在同一個 bucket
- 最後,因為題目要求要找最大的 h-index,所以從最後面的 bucket 往前找。當在該 bucket 的數目,已經大於等於該 bucket 的 index時,就找到最大的 h-index 了
Java(參考方法)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public int hIndex(int[] citations) { | |
final int len = citations.length; | |
final int[] buckets = new int[len+1]; | |
for(final int c : citations) { | |
if(c >= len) { | |
buckets[len]++; | |
} else { | |
buckets[c]++; | |
} | |
} | |
int cnt = 0; | |
for(int i = len; i >= 0; i--) { | |
cnt += buckets[i]; | |
if(cnt >= i) { | |
return i; | |
} | |
} | |
return 0; | |
} | |
} |
Kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
fun hIndex(citations: IntArray): Int { | |
val buckets = IntArray(citations.size+1) {0} | |
for(c in citations) { | |
if(c >= citations.size) { | |
buckets[citations.size] += 1 | |
} else { | |
buckets[c] += 1 | |
} | |
} | |
var sum = 0 | |
for(i in buckets.lastIndex downTo 0) { | |
sum += buckets[i] | |
if(sum >= i) { | |
return i | |
} | |
} | |
return 0 | |
} | |
} |
沒有留言:
張貼留言