forked from ex01tus/leetcode-grind
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHIndex.java
More file actions
50 lines (42 loc) · 1.21 KB
/
HIndex.java
File metadata and controls
50 lines (42 loc) · 1.21 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
package array;
import java.util.Arrays;
/**
* Description: https://leetcode.com/problems/h-index
* Difficulty: Medium
*/
public class HIndex {
/**
* Time complexity: O(n)
* Space complexity: O(n)
*/
public int hIndexViaCountingSort(int[] citations) {
// by definition hIndex can only be in range [0; N]
int[] freqMap = new int[citations.length + 1];
for (int citation : citations) {
freqMap[Math.min(citation, citations.length)]++;
}
// check every possible hIndex, starting from the highest
int citationsNumber = 0;
for (int hIndex = freqMap.length - 1; hIndex >= 0; hIndex--) {
citationsNumber += freqMap[hIndex];
if (citationsNumber >= hIndex) return hIndex;
}
return 0;
}
/**
* Time complexity: O(nlog n)
* Space complexity: O(log n)
*/
public int hIndexViaSorting(int[] citations) {
Arrays.sort(citations);
int hIndex = 0;
for (int i = citations.length - 1; i >= 0; i--) {
if (citations[i] > hIndex) {
hIndex++;
} else {
break;
}
}
return hIndex;
}
}