[LeetCode]H-Index II

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

对排好序的求H index,可以想到采用Binary Search。把搜寻规则稍微改一下。

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


你可能感兴趣的:([LeetCode]H-Index II)