Follow up for H-Index: What if the citations
array is sorted in ascending order? Could you optimize your algorithm?
Hint:
- Expected runtime complexity is in O(log n) and the input is sorted.
这题是之前那道H-Index 求H指数的拓展,输入数组是有序的,让我们在O(log n)的时间内完成计算,看到这个时间复杂度,应该有很敏锐的意识应该用二分查找法,我们最先初始化left和right为0和数组长度len-1,然后取中间值mid,比较citations[mid]和len-mid做比较,如果前者大,则right移到mid之前,反之right移到mid之后,终止条件是left>right,最后返回len-left即可,参见代码如下:
class Solution { public: int hIndex(vector<int>& citations) { int len = citations.size(), left = 0, right = len - 1; while (left <= right) { int mid = 0.5 * (left + right); if (citations[mid] == len - mid) return len - mid; else if (citations[mid] > len - mid) right = mid - 1; else left = mid + 1; } return len - left; } };