H-Index
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.
解法1:使用数组记录每个引用的值有几篇文章
之前的写的没保存,贴一个Java的
public int hIndex(int[] citations) {
int L = citations.length;
if(L<1) return 0;
int[] counts = new int[L+1];
for(int i : citations) {
if(i>L) counts[L]++; //hIndex <= length
else counts[i]++;
}
int res = 0;
for(int k=L; k>=0; k--) { //采用累加的方式计算引用次数,这样就不需要每次更新比自己大的引用数
res += counts[k];
if(res>=k) return k;
}
return 0;
}
解法2:利用快排的思想,每次迭代选择一个枢纽点,使得数组的左侧小于枢纽点,右侧大于枢纽点。如果枢纽点的值大于右侧的数,则尝试对左边迭代找更大的h-index;反之,则在右边找满足条件的hIndex.
int partition(vector<int>& citations, int left, int right){
int mid = (left + right) / 2; //pivot的选择也可以是其他的,对于随机数组而言,选第一个也可以
int pivot = citations[mid];
swap(citations[mid], citations[right]);
int i = left - 1, j = right;
for (;;){
while (citations[++i] < pivot);
while (j > 0 && citations[--j] > pivot); //median3的快排针对长度大于2的数组;这里要加入j的条件防止越界
if (i < j) swap(citations[i], citations[j]);
else break;
}
swap(citations[i], citations[right]);
return i;
}
int hIndex(vector<int>& citations) {
int n = citations.size();
int hIndex = 0;
int left = 0, right = n - 1;
while (left <= right){
int index = partition(citations, left, right);
if (n - index <= citations[index]){ // n-index篇文章有至少n-index次引用
hIndex = n-index;
right = index - 1; //试图找更大的hIndex
}
else left = index + 1;
}
return hIndex;
}
H-Index II
Follow up for H-Index: What if the citations
array is sorted in ascending order? Could you optimize your algorithm?
int hIndex(vector<int>& citations) {
int n = citations.size();
int left = 0;
int right = n - 1;
int hIndex = 0;
while (left <= right){
int half = (left + right) / 2;
if (citations[half] >= n - half){
hIndex = n - half;
right = half - 1;
}
else left = half + 1;
}
return hIndex;
}