LeetCode H-Index II

本文介绍了一种针对已排序引用数组的H-Index算法优化方案。通过对数组进行预处理并利用二分查找技术,该算法能在O(log n)时间内找到满足条件的H-Index值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description:

Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimize your algorithm?

Solution:

The problem is very similar to former one. For last problem, we have notice that there exists a formula: if we order the number in an descending order, then the last index that satisfies the arr[i] >= i+1 is the answer.

And this is very similar in this problem, the only difference is that given the ascending array.

Notice that we can pre-operate the array, and citations[n-1-i] -= i+1, which will maintain the ascending order.

And due to the ascending order, we can use binary-search to find the largest index with citations[index] < 0, so the length or h is n-1-index.

<span style="font-size:18px;">public class Solution {
	public int hIndex(int[] citations) {
		int n = citations.length;

		for (int i = 0; i < n; i++)
			citations[n - 1 - i] -= i + 1;

		if (n == 0)
			return 0;
		if (citations[n - 1] < 0)
			return 0;
		if (citations[0] >= 0)
			return n;

		int l = 0, r = n - 1, mid;
		while (l + 1 < r) {
			mid = (l + r) / 2;
			if (citations[mid] >= 0)
				r = mid;
			else
				l = mid;
		}

		return n - l - 1;
	}
}
</span>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值