题目
给你一个整数数组 citations
,其中 citations[i]
表示研究者的第 i
篇论文被引用的次数。计算并返回该研究者的 h
指数。
根据维基百科上 h 指数的定义:h
代表“高引用次数” ,一名科研人员的 h
指数 是指他(她)至少发表了 h
篇论文,并且每篇论文 至少 被引用 h
次。如果 h
有多种可能的值,h
指数 是其中最大的那个。
示例 1:
输入:citations = [3,0,6,1,5] 输出:3 解释:给定数组表示研究者总共有 5 篇论文,每篇论文相应的被引用了 3,0,6,1,5 次。 由于研究者有 3 篇论文每篇 至少 被引用了 3 次,其余两篇论文每篇被引用不多于 3 次,所以她的 h 指数是 3。
示例 2:
输入:citations = [1,3,1] 输出:1
C++代码
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
/*
* 定义返回h指数函数,数组排序
*定义h的初始值为0,从大到小遍历,如果被引用的次数大于h,
* 说明存在被引用次数至少有h+1次的论文
* h++直到遍历结束
*/
int hIndex(vector<int>& citations) {
sort(citations.begin(), citations.end());
int h = 0;
for (int i = citations.size() - 1; i >= 0; i--) {
if (citations[i] > h) {
h++;
}
}
return h;
}
int main() {
vector<int> citations = { 3,0,6,1,5 };
cout << "citations: ";
for (int i = 0; i < citations.size(); i++) {
cout << citations[i] << " ";
}
cout << endl;
int h = hIndex(citations);
cout << "h指数: " << h << endl;
return 0;
}
分析
定义返回 h 指数函数hIndex(),将数组默认排序,定义 h 的初始值为 0,从大到小遍历,如果被引用的次数大于 h,说明存在被引用次数至少有 h+1 次的论文,h++直到遍历结束。