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.
至少有h篇被人引用h次
- 如果总共的论文数为N则,h最多为N
- 计数排序
int hIndex(int* citations, int citationsSize) { int *array = (int *)malloc((citationsSize + 1) * sizeof(int)); for (int i = 0; i < citationsSize + 1; i++) array[i] = 0; //必须初始化 for (int i = 0; i < citationsSize; i++) { if (citations[i] >= citationsSize) //如果大于最大文章数,则认为最大引用文章值++ array[citationsSize]++; else array[citations[i]]++; } if (array[citationsSize] >= citationsSize) return citationsSize; for (int i = citationsSize - 1; i >= 0; i--) { array[i] = array[i] + array[i + 1]; if (array[i] >= i) return i; } return 0; }
Follow up for H-Index: What if the citations
array is sorted in ascending order? Could you optimize your algorithm?
int hIndex(int* citations, int citationsSize) { int n = 0; if(citations[0] >= citationsSize) return citationsSize; else { for(int i = citationsSize - 1; i >= 0; i--) { if(citations[i] >= citationsSize - i) //如果被引用的次数大于同样次数以上的篇数时 n++; else break; } } return n; }
- 二分查找
int hIndex(int* citations, int citationsSize) { int n = citationsSize; int low = 0, high = citationsSize - 1; while(low <= high) { int mid = low + (high-low) / 2; if(citations[mid] == n - mid) return n-mid; else if(citations[mid] < n - mid) low = mid + 1; else high = mid - 1; } return n-low; }
- n – mid:代表引用次数大于citations[mid]的篇数
- 如果citations[mid] 小于 篇数,则说明至少被引用citations[mid]次的文章数目大于该最小引用的次数