二分答案——H指数(Leetcode 274)

题目选自Leetcode 274. H指数

二分查找(答案)的简单题~

理解题意

image.png

这个例子有点儿特殊,论文被引用了 3 次,篇数有 3 篇。再来看一个更一般的例子:

image.png

结论

这条分割线越靠左边,说明被引用的次数很多,文章还很多,h 指数越高。

在一个有范围的整数区间里中查找一个位置,可以使用二分查找,这件事情通常区别于「在有序数组里查找一个元素的值」,被称为「二分答案」。

方法:二分查找

 

解题代码: 

int judge(int h,int* citations,int n){
	int cnt = 0;
	for(int i=0;i<n;i++)
		if(citations[i] >= h) cnt++;
	return cnt >= h;
}
int hIndex(int* citations, int citationsSize){
    int ans = 0;
    int l=0,r=1001;
	while(l <= r){
		int mid = ( l + r ) / 2;
		if(judge(mid,citations,citationsSize)){ans = mid; l = mid + 1;}
		else r = mid - 1;
	}
	return ans;
}

猜你喜欢

转载自blog.csdn.net/weixin_44572229/article/details/121872936