LeetCode 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.
先来一个直接的,对citations数组排序,然后依次查找大于hidx的文章的数量
class Solution {
public:
int hIndex(vector<int>& citations) {
sort(citations.begin(), citations.end());
int len = citations.size();
int hidx = 0;
int maxh = 0;
for (;; hidx++) {
int idx = lower_bound(citations.begin(), citations.end(), hidx) - citations.begin();
if (len - idx < hidx) {
break;
}
maxh = hidx;
}
return maxh;
}
};
考虑一下可以发现h值必然在[0, citations.size()]之间,当在一个位置i时其可能的h值为citations.size() - i(因为后面的数都大于等于当前位置的数),如果此时citations[i]大于等于这个值那么第一个满足次条件的就是要求的最大h值,因为越到后面citations.size() - i越小。
class Solution {
public:
int hIndex(vector<int>& citations) {
sort(citations.begin(), citations.end());
int len = citations.size();
int maxh = 0;
for (int i=0; i<len; i++) {
int remain = len - i;
if (citations[i] >= remain) {
maxh = remain;
break;
}
}
return maxh;
}
};
当然Hindex II 在排序数组后使用二分搜索可以把查找时间复杂度变为logn,不过这里排序依据用了nlogn,也改变不了:
class Solution {
public:
int hIndex(vector<int>& citations) {
sort(citations.begin(), citations.end());
int len = citations.size();
int lo = 0;
int hi = len;
while (lo < hi) {
int mid = (lo + hi) / 2;
int remain = len - mid;
if (citations[mid] >= remain) {
hi = mid;
} else {
lo = mid + 1;
}
}
return len - lo;
}
};
时间上没什么提升