275 H-Index II

275. H-Index II

1. Question

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

2. Implementation

(1) Binary Search
1
class Solution {
2
public int hIndex(int[] citations) {
3
if (citations == null || citations.length == 0) {
4
return 0;
5
}
6
7
int n = citations.length;
8
int start = 0, end = citations.length - 1, mid = 0;
9
10
while (start + 1 < end) {
11
mid = start + (end - start) / 2;
12
13
if (citations[mid] < n - mid) {
14
start = mid + 1;
15
}
16
else {
17
end = mid;
18
}
19
}
20
21
if (citations[start] >= n - start) {
22
return n - start;
23
}
24
else if (citations[end] >= n - end) {
25
return n - end;
26
}
27
else {
28
return 0;
29
}
30
}
31
}
Copied!

3. Time & Space Complexity

Binary Search: 时间复杂度O(logn), 空间复杂度O(1)