leetcode 275. H-Index II 高引用次数计算2
Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimize your algorithm?
和上一道题一样leetcode 274. H-Index,不过不需要排序,其余的都一样。
代码如下:
/*
* https://baike.baidu.com/item/h-index/3991452?fr=aladdin
* 参见H-Index的百科即可
* 这里是升序,那么就不要排序了
* */
class Solution
{
public int hIndex(int[] citations)
{
if(citations==null || citations.length<=0)
return 0;
//Arrays.sort(citations);
int maxH=0;
for(int i=citations.length-1;i>=0;i--)
{
int count=citations.length-i;
if(citations[i]>=count && count>maxH)
maxH=count;
else
break;
}
return maxH;
}
}
下面是C++的做法,直接按照H-Index的做法即可,代码如下:
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <string>
#include <algorithm>
using namespace std;
class Solution
{
public:
int hIndex(vector<int>& c)
{
//sort(c.begin(),c.end());
int maxH = 0;
for (int i = c.size() - 1; i >= 0; i--)
{
int count = c.size() - i;
if (c[i] >= count && count > maxH)
maxH = count;
}
return maxH;
}
};
还没有评论,来说两句吧...