citations
array is sorted in ascending order? Could you optimize your algorithm?Solution:
The idea is to use binary search to find the first occurrence satisfy:
citations[index] >= citations.length - index.
This condition means there are citations[index] papers have at least citations[index] citations.
The time complexity is O(logn) and the space complexity is O(n).
Code:
public class Solution { public int hIndex(int[] citations) { if (citations == null || citations.length == 0) { return 0; } // find first occurance that citations[index] >= citations.length - index int n = citations.length; int start = 0; int end = n - 1; while (start + 1 < end) { int mid = start + (end - start) / 2; if (citations[mid] >= n - mid) { end = mid; } else { start = mid; } } if (citations[start] >= n - start) { return n - start; } if (citations[end] >= n - end) { return n - end; } return 0; } }