Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit ccdfef5

Browse files
solves h index in java
1 parent 10cb0f3 commit ccdfef5

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

‎README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -223,7 +223,7 @@
223223
| 268 | [Missing Number](https://leetcode.com/problems/missing-number) | [![Java](assets/java.png)](src/MissingNumber.java) [![Python](assets/python.png)](python/missing_number.py) | |
224224
| 270 | 🔒 [Closest Binary Search Tree Value](https://leetcode.com/problems/closest-binary-search-tree-value) | | |
225225
| 271 | 🔒 [Encode and Decode Strings](https://leetcode.com/problems/encode-and-decode-strings) | | |
226-
| 274 | [H-Index](https://leetcode.com/problems/h-index) | | |
226+
| 274 | [H-Index](https://leetcode.com/problems/h-index) | [![Java](assets/java.png)](src/HIndex.java) | |
227227
| 275 | [H-Index II](https://leetcode.com/problems/h-index-ii) | | |
228228
| 276 | 🔒 [Paint Fence](https://leetcode.com/problems/paint-fence) | | |
229229
| 277 | 🔒 [Find The Celebrity](https://leetcode.com/problems/find-the-celebrity) | | |

‎src/HIndex.java

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// https://leetcode.com/problems/h-index
2+
// T: O(N)
3+
// S: O(N)
4+
5+
import java.util.HashMap;
6+
import java.util.Map;
7+
8+
public class HIndex {
9+
public int hIndex(int[] citations) {
10+
final Map<Integer, Integer> citationFrequencies = getFrequencies(citations);
11+
final int maxCitation = max(citations);
12+
for (int hIndex = maxCitation, papers = 0 ; hIndex >= 0 ; hIndex--) {
13+
papers += citationFrequencies.getOrDefault(hIndex, 0);
14+
if (papers >= hIndex) return hIndex;
15+
}
16+
return 0;
17+
}
18+
19+
private int max(int[] array) {
20+
int result = 0;
21+
for (int element : array) {
22+
result = Math.max(result, element);
23+
}
24+
return result;
25+
}
26+
27+
private Map<Integer, Integer> getFrequencies(int[] array) {
28+
final Map<Integer, Integer> frequencies = new HashMap<>();
29+
for (int element : array) {
30+
frequencies.put(element, frequencies.getOrDefault(element, 0) + 1);
31+
}
32+
return frequencies;
33+
}
34+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /