题目274:
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.
class Solution {
public int hIndex(int[] citations) {
//给定论文引用次数组数,h指数:有h篇论文分别被引用了至少h次,其余N-h篇的引用次数均不超过h次,返回h指数
//思路:对数组进行排序,求出该位置的引用次数是否大于i+1的下标
if(citations==null||citations.length==0)return 0;
Arrays.sort(citations);
for(int i=0;i<citations.length;i++){
if(citations[i]>=citations.length-i){
//该位置已经满足条件,后面均满足
return citations.length-i;
}
}
return 0;
}
}
分析2(时间复杂度n,更快):
class Solution {
public int hIndex(int[] citations) {
//给定论文引用次数组数,h指数:有h篇论文分别被引用了至少h次,其余N-h篇的引用次数均不超过h次,返回h指数
//思路:利用计数统计的方式来存储各篇论文的引用次数
int len=citations.length;
//因为有可能文章的饮用次数大于数组长度
int [] count=new int[len+1];
for(int i=0;i<len;i++){
if(citations[i]>=len){
count[len]++;
}else{
count[citations[i]]++;
}
}
//统计其中大于当前论文数量的个数
int total=0;
for(int i=len;i>=0;i--){
//统计个数,如果当前大于前面的个数,说明total就是满足条件的解
total+=count[i];
if(total>=i){
return i;
}
}
return 0;
}
}
题目275:
Follow up for H-Index: What if the citations
array is sorted in ascending order? Could you optimize your algorithm?
分析:
class Solution {
public int hIndex(int[] citations) {
//因为数组已经有序,只需要判定当前判定位置是否大于citations.length-i即可
//思路:有序的数组,肯定是使用二分查找,mid至少满足上述判定条件即可
//分析:未考虑第一个数据就满足情况
int low=0,high=citations.length-1;
while(low<=high){
int mid=(low+high)/2;
//1.判定条件需要满足,恰恰mid的前一个不满足判定条件,2.需要考虑mid为第一个元素,即满足情况
if((mid>0&&citations[mid]>=citations.length-mid&&citations[mid-1]<citations.length-(mid-1))||(mid==0&&citations[mid]>=citations.length-mid))
{
return citations.length-mid;
}else if(citations[mid]>citations.length-mid){
high=mid-1;
}else {
low=mid+1;
}
}
return 0;
}
}