分析
难度 中
来源 https://leetcode.com/problems/h-index/
思路1
If we have the function f ordered in decreasing order from the largest value to the lowest one, we can compute the h index as follows:
思路2
The idea behind it is some bucket sort mechanisms. First, you may ask
why bucket sort. Well, the h-index is defined as the number of papers
with reference greater than the number. So assume n is the total
number of papers, if we have n+1 buckets, number from 0 to n, then for
any paper with reference corresponding to the index of the bucket, we
increment the count for that bucket. The only exception is that for
any paper with larger number of reference than n, we put in the n-th
bucket.
题目
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
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, her h-index is 3.
Note: If there are several possible values for h, the maximum one is taken as the h-index.
解答
package LeetCode;
public class L274_H_Index {
/* public int hIndex(int[] citations) {//citations中的下标是从1开始算的,实际存储是从0开始的。
int len=citations.length;
if(len==0)
return 0;
Arrays.sort(citations);
int hIndex=0;
for(int i=0;i<len;i++){
int temp=Math.min(citations[len-1-i],i+1);
if(hIndex<temp)
hIndex=temp;
else
break;//后边的i会越来越小,没必要接着算
}
return hIndex;
}*/
public int hIndex(int[] citations) {//citations中的下标是从1开始算的,实际存储是从0开始的。
int n=citations.length;
int hindex=0;
int[] buckets=new int[n+1];
for(int i=0;i<n;i++)
{
if(citations[i]>=n){//存储引用大于等于n的文章数
buckets[n]++;
}
else
buckets[citations[i]]++;//存储引用为citations[i]的文章数
}
int sum=0;
for(int i=n;i>=0;i--){
sum+=buckets[i];//引用数大于等于i的文章数
//System.out.println(i);
if(sum>=i)//引用数大于文章数的最大值。
{
hindex=i;
break;
}
}
return hindex;
}
public static void main(String[] args){
L274_H_Index l274=new L274_H_Index();
//int[] citations = {3,0,6,1,5};
int[] citations = {10,8,5,4,3};//期望输出 4
//int[] citations = {25,8,5,3,3};//期望输出 3
//int[] citations = {100};//期望输出 1
System.out.println(l274.hIndex(citations));
}
}