leecode 解题总结:275. H-Index II

#include <iostream>
#include <stdio.h>
#include <vector>
#include <string>
using namespace std;
/*
问题:
Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimize your algorithm?

分析:题目给定了是升序,问如何进行优化。之前就是先排序。
均篇引用次数>=h的至少有h篇,引用次数>=篇数
从后向前:    nums[i] >= n - i就继续寻找直到找到不满足,上一次记录的值即为所求
期望运行时间为O(logN),
如果采用二分法:对于mid
nums[mid] < n - mid:说明mid不可能,low = mid + 1
nums[mid] >= n - mid:
           如果有:nums[mid-1] < n - (mid-1),则篇数size - mid即为所求
		   否则:当前位置不可能,high=mid-1

输入:
5(数组元素个数)
0 1 3 5 6
1
100
输出:
3
1

关键:
1 均篇引用次数>=h的至少有h篇,引用次数>=篇数
从后向前:    nums[i] >= n - i就继续寻找直到找到不满足,上一次记录的值即为所求
期望运行时间为O(logN),
如果采用二分法:对于mid
nums[mid] < n - mid:说明mid不可能,low = mid + 1
nums[mid] >= n - mid:
           如果有:nums[mid-1] < n - (mid-1),则篇数size - mid即为所求
		   否则:当前位置不可能,high=mid-1
*/

class Solution {
public:

    int hIndex(vector<int>& citations) {
		if(citations.empty())
		{
			return 0;
		}
		int size = citations.size();
		int low = 0;
		int high = size - 1;
		int mid;
		while(low < high)
		{
			mid = low + (high - low) / 2;
			if(citations.at(mid) < size - mid)
			{
				low = mid + 1;
			}
			else
			{
				//找到了
				if(mid - 1 >= 0 && citations.at(mid-1) < size - (mid - 1))
				{
					return (size - mid);
				}
				else
				{
					high = mid - 1;
				}
			}
		}
		//如果low = high,
		if(citations.at(low) >= size - low)
		{
			return (size - low);
		}
		else
		{
			return 0;
		}
    }
};

void print(vector<int>& result)
{
	if(result.empty())
	{
		cout << "no result" << endl;
		return;
	}
	int size = result.size();
	for(int i = 0 ; i < size ; i++)
	{
		cout << result.at(i) << " " ;
	}
	cout << endl;
}

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值