leetcode 274. H-Index

来源:互联网 发布:如何自学软件编程 编辑:程序博客网 时间:2024/06/05 04:37

第一种比较直接的想法,但往往不是最简单的,先排序然后一个一个对应,但往往这种情况下不会是最好的办法

static bool comp(int a, int b){    return !(a<b);}int hIndex(vector<int>& citations) {    citations.push_back(INT_MAX);    sort(citations.begin(), citations.end(), Solution::comp);    int temp=0;    for (int i = 1; i < citations.size(); i++)    {        if (citations[i] >= i)            temp = i;    }    return temp;}

第二种办法 利用一个性质一共n个数,他的H-index一定不会超过n;然后从后往前处理
int hIndex(vector& citations) {
int n = citations.size();
if (!n)
return 0;
vector record(n+1, 0); //以前想的是申请最大的数对应大小的空间,但这步是多余的
for (int i = 0; i < n; i++)
if (citations[i] >= n)
record[n]++;
else
record[citations[i]]++;
int count = 0;
for (int i = n; i >= 0; i–)
{
count += record[i]; //这一步是紧跟定义,有点绕,但是想清楚了就行。。。
if (count >= i)
return i;
}
}
There are always better solutions for us beginners.