H-Index II 二分查找

来源:互联网 发布:和英国女人 知乎 编辑:程序博客网 时间:2024/05/16 18:46

H-Index II

 

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

Hint:

  1. 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;    }};
0 0