给你一个整数数组 citations ,其中 citations[i] 表示研究者的第 i 篇论文被引用的次数。计算并返回该研究者的 h 指数。h 指数的定义:h 代表“高引用次数”(high citations),一名科研人员的 h 指数是指他(她)的 (n 篇论文中)总共有 h 篇论文分别被引用了至少 h 次。且其余的 n - h 篇论文每篇被引用次数 不超过 h 次。
例如:某人的 h 指数是 20,这表示他已发表的论文中,每篇被引用了至少 20 次的论文总共有 20 篇。提示:如果 h 有多种可能的值,h 指数 是其中最大的那个。
方法一:排序
使用sort排序,得到从小到大的数组,使用循环,逆序遍历,从n-1~0(数组下标);只要保证遍历过程中,前h个大于h,就得到了当前的h指数
class Solution {
public:
int hIndex(vector<int>& citations) {
int n = citations.size();
int h = 0;
sort(citations.begin(),citations.end());
for(int i=n-1;i>=0;i--){
if(citations[i]>h){ //这里不能>=h
h++;
}
}
return h;
}
};
// 3 0 6 1 5
// 0 1 3 5 6 h=0
// 6 >0 h=1
// 5 >1 h=2
// 3 >2 h=3
// 1 !>2 输出h=3
方法一:暴力哈希
默认哈希表的value=0,遍历数组分辨求出数组中元素大于等于1 2 3 4 5 6...n的个数
3 0 6 1 5
<1,4><2,3><3,3> >>>>>求得大于等于3的个数是3个,h=3
1 3 1
<1,3><2,1> >>>>>大于1的个数有3个满足大于的个数至少有一个 h=1
满足左值小于等于右值的同时,选择左值大的
class Solution {
public:
int hIndex(vector<int>& citations) {
int n = citations.size();
int h = 0;
unordered_map<int,int> mp(0);
for(int i=1;i<=n;++i){
for(int j =0;j<n;++j){
if(citations[j]>=i){
mp[i]++;
}
}
}
for(auto & k:mp){
int tmp = 0;
if(k.first<=k.second){
tmp = k.first;
}
h = max(h,tmp);
}
return h;
}
};