275 H-Index II

1. Question

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

2. Implementation

(1) Binary Search

class Solution {
    public int hIndex(int[] citations) {
        if (citations == null || citations.length == 0) {
            return 0;
        }

        int n = citations.length;
        int start = 0, end = citations.length - 1, mid = 0;

        while (start + 1 < end) {
            mid = start + (end - start) / 2;

            if (citations[mid] < n - mid) {
                start = mid + 1;
            }
            else {
                end = mid;
            }
        }

        if (citations[start] >= n - start) {
            return n - start;
        }
        else if (citations[end] >= n - end) {
            return n - end;
        }
        else {
            return 0;
        }
    }
}

3. Time & Space Complexity

Binary Search: 时间复杂度O(logn), 空间复杂度O(1)

Last updated