275 H-Index II H指数 II

这是 H指数 进阶问题:如果citations 是升序的会怎样?你可以优化你的算法吗?

详见:https://leetcode.com/problems/h-index-ii/description/

Java实现:

class Solution {
    public int hIndex(int[] citations) {
        int n=citations.length;
        int l=0;
        int r=n-1;
        while(l<=r){
            int m=(l+r)>>1;
            if(citations[m]==n-m){
                return n-m;
            }else if(citations[m]>n-m){
                r=m-1;
            }else{
                l=m+1;
            }
        }
        return n-l;
    }
}

C++实现:

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

 参考:https://www.cnblogs.com/grandyang/p/4782695.html

posted on 2018-04-09 17:34  lina2014  阅读(116)  评论(0编辑  收藏  举报

导航