您的位置:首页 > 其它

H-Index II 二分查找

2015-09-09 14:10 190 查看


H-Index II

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.

class Solution {
public:
//因为是排好序的 然后要求O(logn),则想到用二分查找
    int hIndex(vector<int>& citations) {
        
        int len=citations.size();
        if(len<=0)
            return 0;
        int mid,left=0,right=len-1;
        while(left<=right)
        {
            mid=left+(right-left)/2;
            if(len-mid==citations[mid])
                return len-mid;
            else if(citations[mid]<len-mid)
                left=mid+1;
            else
                right=mid-1;
        }
        return len-left;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: