Leetcode 274. H-Index & Round H H-index-Kick Start 2019

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.”

Example:
Input: citations = [3,0,6,1,5]
Output: 3
Explanation: [3,0,6,1,5] 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, her h-index is 3.

题目大意:给出一个有n个数的数组,数组中的数代表研究者的一篇文章的引用量,求出该研究者的h指数。h指数的定义就是作者的N篇文章中至少有h篇文章的引用量大于等于h,其他N-h篇文章引用量都小于h。
思路1:直接对数组进行排序,从大到小遍历,h指数等于达到当前位置已经遍历了的元素的个数,在遍历过程中不断判断当前文章的引用量能不能再提升h指数,不能则停止,能则继续遍历。这个方法可以看作是一个简单模拟,模拟人工看的过程。
代码如下:

class Solution {
public:
    int hIndex(vector<int>& citations) {
        int ans = 0, n = citations.size();
        if(n == 0)
            return ans;
        sort(citations.begin(), citations.end());
        for(int i = n-1;i >= 0; i--){
            if(citations[i] >= n-i && ans < n-i)
                ans = n-i;
            else
                break;
        }
        return ans;
    }
};

思路2:kick-start的题目要求遍历到每一篇文章时都输出当前的h指数,输入输出如下:

2
3
5 1 2
6
1 3 3 2 2 15
Case #1: 1 1 2
Case #2: 1 1 2 2 2 3

这种情况下刚才的思路就很难ac了,刚才是在接受所有输出后统一排序,也就是在最后计算h指数时才决定哪些文章是对h指数做出贡献了的,但是这次要在遍历数组的过程中决定哪些文章对h指数做出贡献,也就是在遍历过程中就要对文章进行判断,它是否可能使h指数提升,将不可能对h指数进行提升的文章剔除,根据以上思路,可以使用优先队列解决这个问题。参考链接

#include <bits/stdc++.h>
using namespace std;
 
int main(int argc, char const *argv[])
{
	int N, caseNum = 0;
	cin >> N;
	while(N--){
		int n;
		cin >> n;
		vector<int> a(n);
		for(int i = 0;i < n; i++)
			cin >> a[i];
		priority_queue<int> pq;
		cout << "Case #" << ++caseNum << ": ";
		for(int i = 0;i < n; i++){
			pq.push(-a[i]);
			int top = - pq.top();
			if(top < pq.size()){
				pq.pop();
			}
			cout << pq.size();
			if(i != n-1)
				cout << " ";
		}
		cout << endl;
	}
	
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值