-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathHIndex.java
More file actions
52 lines (49 loc) · 1.41 KB
/
HIndex.java
File metadata and controls
52 lines (49 loc) · 1.41 KB
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
public class HIndex {
//Naive solution. O(nlogn) time
public int hIndex0(int[] citations) {
Arrays.sort(citations);
int i = 1;
for(; i <= citations.length && i <= citations[citations.length - i]; ++i);
return i - 1;
}
//Linear solution.
public int hIndex1(int[] citations) {
int maxNum = 0;
for (int citation : citations) {
maxNum = Math.max(maxNum, citation);
}
int[] counts = new int[maxNum + 1];
for (int citation : citations) {
counts[citation]++;
}
int i = maxNum;
for (; i >= 0; --i) {
if (i < maxNum) {
counts[i] += counts[i + 1];
}
if (counts[i] >= i) {
break;
}
}
return i;
}
//Improve the above solution to get the best O(n) solution.
public int hIndex(int[] citations) {
int[] counts = new int[citations.length + 1];
for (int citation : citations) {
if (citation >= citations.length) {
counts[citations.length]++;
} else {
counts[citation]++;
}
}
int countAbove = 0;
for (int h = counts.length - 1; h >= 0; --h) {
countAbove += counts[i];
if (countAbove >= h) {
return h;
}
}
return 0;
}
}