I. 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.
Runtime: 4ms.
1 class Solution { 2 public: 3 int hIndex(vector<int>& citations) { 4 int n = citations.size(); 5 if(n == 0) return 0; 6 7 int i = 1; 8 sort(citations.begin(), citations.end()); 9 while(i <= n){ 10 while(citations[n - i] >= i) 11 i++; 12 return i - 1; 13 } 14 return citations[0]; 15 } 16 };
II. Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimize your algorithm?
Runtime: 12ms.
1 class Solution { 2 public: 3 int hIndex(vector<int>& citations) { 4 int n = citations.size(); 5 if(n == 0) return 0; 6 7 int low = 0, high = n - 1; 8 while(low <= high){ 9 int mid = (low + high) / 2; 10 11 if(n - mid <= citations[mid]) 12 high = mid - 1; 13 else 14 low = mid + 1; 15 } 16 return n - low; 17 } 18 };
原文:http://www.cnblogs.com/amazingzoe/p/4834094.html