[LeetCode]H-Index

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.

N篇大于等于N个引用的文章,则返回N。

排序O(nlogn)。

 1 class Solution {
 2 public:
 3     int hIndex(vector<int>& citations) {
 4         if(citations.size()==0) return 0;
 5         int n = citations.size();
 6         sort(citations.begin(),citations.end());
 7         for(int i=0;i<n;i++)
 8         {
 9             if(citations[i]>=(n-i)) return (n-i);
10         }
11         return 0;
12     }
13 };

不排序也可以,需要O(n)的空间,储存n次引用的文章数目。

 1 class Solution {
 2 public:
 3     int hIndex(vector<int>& citations) {
 4         if(citations.size()==0) return 0;
 5         int n = citations.size();
 6         vector<int> sign(n+1,0);
 7         for(int i=0;i<n;i++)
 8         {
 9             if(citations[i]>=n)
10             {
11                 sign[n]++;
12             }
13             else
14             {
15                 sign[citations[i]]++;
16             }
17         }
18         if(sign[n]>=n) return n;
19         for(int i=n-1;i>=0;i--)
20         {
21             sign[i]=sign[i]+sign[i+1];
22             if(sign[i]>=i) return i;
23         }
24         return 0;
25     }
26 };
原文地址:https://www.cnblogs.com/Sean-le/p/4806413.html