ollow up for H-Index: What if the
citations
array is sorted in ascending order? Could you optimize your algorithm?
Hint:
- Expected runtime complexity is in O(log n) and the input is sorted.
Since the problem asks for a O(log n) solution, we can think of using a binary search.
Code (Java):
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 30 31 32 33 | public class Solution { public int hIndex( int [] citations) { if (citations == null || citations.length == 0 ) { return 0 ; } int lo = 0 ; int hi = citations.length - 1 ; int len = citations.length; while (lo + 1 < hi) { int mid = lo + (hi - lo) / 2 ; if (citations[mid] == len - mid) { return len - mid; } else if (citations[mid] < len - mid) { lo = mid; } else { hi = mid; } } if (citations[lo] >= len - lo) { return len - lo; } if (citations[hi] >= len - hi) { return len - hi; } return 0 ; } } |
No comments:
Post a Comment