Leetcode 275. H-Index II

2018-01-12 14:35:27 浏览数 (1)

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

接上一篇,数组升序排列。

一看就是二分,需要注意边界,仔细想想。

代码语言:javascript复制
class Solution {
public:
    int hIndex(vector<int>& citations) {
        int mid = -1, l = 0, r = citations.size()-1;
        while(l <= r)
        {
            mid = (l   r) >> 1;
            if(citations.size() - mid == citations[mid]) return citations[mid];
            else if(citations.size() - mid > citations[mid]) l = mid   1;
            else r = mid - 1;
        }
        return citations.size() - r - 1;
    }
};

0 人点赞