[Leetcode] 275. H-Index II 解题报告

来源:互联网 发布:预科生的贩毒网络豆瓣 编辑:程序博客网 时间:2024/05/18 17:26

题目

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

思路

做这道题目的时候,我才发现上一道题目其实排序后可以利用二分查找将时间复杂度降为O(logn)。和普通二分取中不同的是,我们关注的大于citations[mid]的文章数和citations[mid]的关系,根据这个关系不断缩小搜索范围。

代码

class Solution {public:    int hIndex(vector<int>& citations) {        int size = citations.size(), left = 0, right = size - 1;        while (left <= right) {            int mid = left + (right - left) / 2;            int count = size - mid;            if (citations[mid] < count) {                left = mid + 1;            }            else {                right = mid - 1;            }        }        return size - left;    }};