Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimize your algorithm?
复杂度
时间 O(logN) 空间 O(1)
要求时间复杂度是O(logN) , 只能用二分法了, 其实, 对于排序好的数组多用二分法和双指针.
public int hIndex(int[] citations) {
if (citations == null || citations.length == 0) {
return 0;
}
int ans = 0, n = citations.length;
int beg = 0, end = citations.length - 1;
while (beg + 1 < end) {
int mid = beg + (end - beg) / 2;
if (citations[mid] == n - mid) {
return citations[mid];
} else if (citations[mid] < n - mid) {
beg = mid;
} else {
ans = Math.max(n - mid, ans);
end = mid;
}
}
if (citations[beg] >= n - beg) {
ans = Math.max(n - beg, ans);
}
if (citations[end] >= n - end) {
ans = Math.max(n - end, ans);
}
return ans;
}