leecode 解题总结:274. H-Index

来源:互联网 发布:java开发常见问题 编辑:程序博客网 时间:2024/05/29 03:32
#include <iostream>#include <stdio.h>#include <vector>#include <string>#include <map>#include <unordered_map>#include <algorithm>using namespace std;/*问题:Given an array of citations (each citation is a non-negative integer) of a researcher, write a function tocompute 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."For example, given citations = [3, 0, 6, 1, 5], which 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, his h-index is 3.Note: If there are several possible values for h, the maximum one is taken as the h-index.分析:高被引次数为h表示至少有h篇文章引用次数都>=h,其余N-h篇文章引用次数<=h。就是以h作为统计的分割点。那么其实取值返回就是[0,最高引用次数]比如[0,0,0],那么h=0比如[5,5,5,5,5],那么h=5如果采用暴力破解,初始选择引用次数最多的作为h,统计h出现的次数,如果次数< h,则h--。输入:5(数组元素个数)3 0 6 1 51100输出:31Input:[100]Output:0Expected:1出错的原因在于:尝试的引用次数不是递减的,而是map中的键高被引次数最多不会超过文章个数,关键:leecode提示先排序,计算可能的值,使用额外空间参考解法:http://www.cnblogs.com/zslhq/p/5954582.html1、排序,从后向前遍历,对于当前元素i,存储到集合中,此时引用次数为nums[i],篇数为n-i,判断其是否满足至少有h篇文章引用次数>=h引用次数>=h nums[i](引用次数) >= n-i(篇数)举例:3 0 6 1 5,排序后: 0 1 3 5 62、不排序的方法就是采用统计排序,先计算最大值,然后统计,统计后从后向前仍然采用上述方式至少有h篇引用次数>=h(篇数),即引用次数>=篇数篇数可以统计,引用次数为当前值*/class Solution {public:    int hIndex2(vector<int>& citations) {if(citations.empty()){return 0;}sort(citations.begin() , citations.end());int size = citations.size();int result = 0;for(int i = size - 1 ; i >= 0 ; i--){//满足至少有引用次数>=h(篇数),记录结果if( citations.at(i) >= size - i ){result = size - i;}else{break;}}return result;    }};void process(){ vector<int> nums; int value; int num; Solution solution; vector<int> result; while(cin >> num ) { nums.clear(); for(int i = 0 ; i < num ; i++) { cin >> value; nums.push_back(value); } int answer = solution.hIndex(nums); cout << answer << endl; }}int main(int argc , char* argv[]){process();getchar();return 0;}

0 0
原创粉丝点击