-
Notifications
You must be signed in to change notification settings - Fork 16
/
HIndex.java
34 lines (30 loc) · 1014 Bytes
/
HIndex.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
34
// https://leetcode.com/problems/h-index
// T: O(N)
// S: O(N)
import java.util.HashMap;
import java.util.Map;
public class HIndex {
public int hIndex(int[] citations) {
final Map<Integer, Integer> citationFrequencies = getFrequencies(citations);
final int maxCitation = max(citations);
for (int hIndex = maxCitation, papers = 0 ; hIndex >= 0 ; hIndex--) {
papers += citationFrequencies.getOrDefault(hIndex, 0);
if (papers >= hIndex) return hIndex;
}
return 0;
}
private int max(int[] array) {
int result = 0;
for (int element : array) {
result = Math.max(result, element);
}
return result;
}
private Map<Integer, Integer> getFrequencies(int[] array) {
final Map<Integer, Integer> frequencies = new HashMap<>();
for (int element : array) {
frequencies.put(element, frequencies.getOrDefault(element, 0) + 1);
}
return frequencies;
}
}