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."
For example, given
citations = [3, 0, 6, 1, 5]
, which 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, his h-index is 3
.
Note: If there are several possible values for
h
, the maximum one is taken as the h-index.
Hint:
- An easy approach is to sort the array first.
- What are the possible values of h-index?
- A faster approach is to use extra space.
我是看了第二条hint才想到的。这属于结果在一个小范围内的题。
因为可能的h-index 最大也就是n
那么构造一个count 数列,如果citation次数大于n,count加到count[n]上,else 记录那个citation[i](例如5)的count 次数。
想要知道最大count >= i, 从右边向左扫,count[i-1]+=count[i]
public int hIndex(int[] citations) {
int n = citations.length;
int[] count = new int[n+1];
for(int i = 0; i < n; i++){
if(citations[i] >= n)
count[n]++;
else
count[citations[i]]++;
}
for(int i = n; i> 0; i--){
if(count[i] >= i) return i;
count[i-1] += count[i];
}
return 0;
}
Could you optimize your algorithm?
解法:
citations[i]来说,这个位置的结果是Math.min(n-i,citations[i])
,因此就是找位置使得Math.min(n-i,citations[i])最大。
当citations[i]值比右边的个数大的时候,结果不可能在这个位置的右边,
即左边还有提高H-index的空间,因为count还有上升空间。
当citations[i]值比右边的个数小的时候,结果不可能在这个位置的左边。
看了hint才知道,因为是sorted array 可以binary search
解法:
citations[i]来说,这个位置的结果是Math.min(n-i,citations[i])
,因此就是找位置使得Math.min(n-i,citations[i])最大。
当citations[i]值比右边的个数大的时候,结果不可能在这个位置的右边,
即左边还有提高H-index的空间,因为count还有上升空间。
当citations[i]值比右边的个数小的时候,结果不可能在这个位置的左边。
看了hint才知道,因为是sorted array 可以binary search
public int hIndex(int[] citations) {
int lo = 0, n =citations.length ,hi = n-1, mid =0,max = 0;
while(lo <= hi){
mid = lo + (hi - lo)/2;
if(citations[mid]==n-mid){
return n-mid;
}else if(citations[mid]>n-mid){
max = Math.max(max,n-mid);
hi = mid - 1;
}else{
max = Math.max(max,citations[mid]);
lo = mid + 1;
}
}
return max;
}
没有评论:
发表评论