275. H-Index II

Follow up for 第274题[H-Index] http://www.jianshu.com/p/571bf9481ede
What if the citations array is sorted in ascending order? Could you optimize your algorithm?

Solution:Binary Search

思路: 二分长度查找mid处的citations[mid]是否已经可以满足条件(citations大于它的(它的右边)已经有citations[mid]个paper数量[通过长度判断]),满足的话继续往左边part找,不满足往右边part找
[0 2 3 5 6 8]
pattern: 满足 满足 满足 不满足 不满足 不满足
Time Complexity: O(logN) Space Complexity: O(1)

Solution Code:

class Solution {
    public int hIndex(int[] citations) {
        int length = citations.length;
        if(length == 0) return 0;
        if(length == 1) return citations[0] >= 1 ? 1 : 0;
        
        int start = 0, end = length - 1;
        while(start <= end) {
            int mid = start + (end - start) / 2;
            if(citations[mid] == (length - mid)) return citations[mid];
            else if(citations[mid] > (length - mid)) end = mid - 1;
            else start = mid + 1;
        }
        return length - (end + 1); 
    }
}

你可能感兴趣的:(275. H-Index II)