Skip to content

Commit 37d660f

Browse files
committed
Added H Index
1 parent 5f998cd commit 37d660f

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed

src/h_index.rs

+65
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
/// Given an array of integers `citations` where `citations[i]` is the number
2+
/// of citations a researcher received for their `ith` paper, return the
3+
/// researcher's h-index.
4+
///
5+
/// According to the definition of h-index on Wikipedia: The h-index is defined
6+
/// as the maximum value of `h` such that the given researcher has published
7+
/// at least `h` papers that have each been cited at least `h` times.
8+
struct Solution;
9+
10+
impl Solution {
11+
12+
pub fn h_index(citations: Vec<i32>) -> i32 {
13+
let n = citations.len();
14+
let mut times = vec![0; n+1];
15+
16+
for cite in citations {
17+
let value = (cite as usize).min(n);
18+
times[value] += 1;
19+
}
20+
21+
let mut count = 0;
22+
let mut index = n;
23+
let mut result = 0;
24+
25+
while index > 0 {
26+
let value = times[index];
27+
count += value;
28+
if count >= index {
29+
result = index as i32;
30+
break;
31+
}
32+
index -= 1;
33+
}
34+
35+
result
36+
}
37+
38+
}
39+
40+
#[cfg(test)]
41+
mod tests {
42+
use super::Solution;
43+
44+
#[test]
45+
fn example_1() {
46+
let citations = vec![3,0,6,1,5];
47+
let result = Solution::h_index(citations);
48+
assert_eq!(result, 3);
49+
}
50+
51+
#[test]
52+
fn example_2() {
53+
let citations = vec![1,3,1];
54+
let result = Solution::h_index(citations);
55+
assert_eq!(result, 1);
56+
}
57+
58+
#[test]
59+
fn real_world_1() {
60+
let citations = vec![4,4,0,0];
61+
let result = Solution::h_index(citations);
62+
assert_eq!(result, 2);
63+
}
64+
65+
}

src/lib.rs

+2
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,8 @@ pub mod graph_valid_tree; // 261
119119

120120
pub mod closest_binary_search_tree_value; // 270
121121

122+
pub mod h_index; // 274 ✓
123+
122124
pub mod move_zeroes; // 283
123125

124126
pub mod find_median_from_data_stream; // 295

0 commit comments

Comments
 (0)