LeetCode 275. H-Index II

111 阅读1分钟

我们需要注意退出while循环的条件是只剩一个元素,但是退出循环以后并不能直接返回n - left的长度,因为我们还要考虑输入数组为[0]的情况,因此必须做一个检查,万一唯一的元素也不符合,就返回0.

class Solution {
    public int hIndex(int[] citations) {
        /** 
        * Given a sorted list citations of size n in ascending order, 
        * one is asked to find the first number citations[i] which meets 
        * the constraint of citations[i] >= n - i.
        */
        if(citations.length == 0){
            return 0;
        }
        int n = citations.length;
        int l = 0, r = n - 1;
        while(l < r){
            int m = l + (r - l) / 2;
            if(citations[m] == n - m){
                return n - m;
            }else if(citations[m] < n - m){
                l = m + 1;
            }else{
                r = m;
            }
        }
        // Post-processing when only one element is left
        if(citations[l] >= n - l){
            return n - l;
        }else{
            return 0;
        }
    }
}