[LeetCode] 275. H-Index II
Follow up for H-Index: What if the
Time complexity: O(logn).
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
Post a Comment