题目:
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篇至少有h次引用,其他N-h篇论文不超过(小于等于)h次引用(取满足条件的最大的h值)。
思路:
1、先排序,判断如果有数字满足citations[i] >= len-i 则它满足条件。意思是至少有len-i篇论文引用次数不低于len-i。
比如1,2,3,4,5,6,则结果是3,至少有3篇论文引用次数大于等于3,其他3篇论文引用次数小于等于3.
2、O(n)的解法。见下面代码。
代码1:
- class Solution {
- public:
- int hIndex(vector<int>& citations)
- {
- sort(citations.begin() , citations.end());
- int len = citations.size();
- for(int i = 0 ; i < len ; i++)
- {
- if(citations[i] >= len - i)
- return len - i;
- }
- return 0;
- }
- };
代码2:
- class Solution {
- public:
- int hIndex(vector<int>& citations)
- {
- if(citations.empty())
- return 0;
- int len = citations.size();
- vector<int> help(len+1 , 0); //help[len]用来统计引用次数超过len的次数
- for(int i = 0 ; i < len ; i++)
- {
- if(citations[i] >= len)
- help[len]++;
- else
- help[citations[i]]++;
- }
- int count = 0;
- for(int i = len ; i >= 0 ; i--)
- {
- count += help[i];//count保存的是引用次数超过某个数字的论文数量
- //count >= i表示引用次数超过i的论文数量
- if(count >= i)
- return i;
- }
- return 0;
- }
- };