[LeetCode] 275. H-Index II

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

Thought process:
Binary search. Compare citations[mid] with citations.length - mid. If citations[mid] >= citations.length - mid, that means the h-index is at least Math.min(citations.length - mid, nums[mid]). Keep the first half of the array. Otherwise keep the second half. 

Solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class Solution {
    public int hIndex(int[] citations) {
        if (citations.length == 0) {
            return 0;
        }
        
        int h = 0;
        int length = citations.length;
        int left = 0;
        int right = length - 1;
        
        while (left + 1 < right) {
            int mid = left + (right - left) / 2;
            if (citations[mid] >= length - mid) {
                h = Math.max(h, length - mid);
                right = mid;
            } else {
                left = mid;
            }
        }
        
        if (citations[left] >= length - left) {
            h = length - left;
        } else if (citations[right] >= length - right) {
            h = length - right;
        }
        return h;
    }
}

Time complexity: O(logn).

Comments

Popular posts from this blog

[LeetCode] 714. Best Time to Buy and Sell Stock with Transaction Fee

[LeetCode] 269. Alien Dictionary

[LeetCode] 631. Design Excel Sum Formula