November 14, 2023

Viiisit [LeetCode] - 274. H-Index

#javascript#ruby

keep learning, keep coding!

Problem - H-Index

Given an array of integers citations where citations[i] is the number of citations a researcher received for their ith paper, return the researcher’s h-index.

According to the definition of h-index on Wikipedia: The h-index is defined as the maximum value of h such that the given researcher has published at least h papers that have each been cited at least h times.

翻譯蒟蒻

本題旨在找出一位研究者的 h 指數,h 指數是指一位研究者的論文中至少有 h 篇被引用了至少 h 次,且其他論文被引用次數不超過 h。


Solution - JavaScript

Solution 1:
(Runtime - 61ms)

1
2
3
4
5
6
7
8
9
10
var hIndex = function(citations) {
citations.sort((a, b) => a - b);
let h = 0;
for (let i = 0; i < citations.length; i++) {
if (citations[i] >= citations.length - i) {
h = Math.max(h, citations.length - i)
}
}
return h;
};

Solution 2:
(Runtime - 54ms)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* @param {number[]} citations
* @return {number}
*/
var hIndex = function(citations) {
citations.sort((a, b) => a - b);
let h = 0;
for (let i = citations.length - 1; i >= 0; i--) {
if (citations[i] >= citations.length - i) {
h = citations.length - i;
}
}
return h;
};

Solution - Ruby

Solution 1:

1
2
3
4
5
6
7
8
9
10
def h_index(citations)
citations.sort!
h = 0
citations.each_with_index do |citation, i|
if citation >= citations.length - i
h = [h, citations.length - i].max
end
end
h
end

Solution 2:

1
2
3
4
5
6
7
8
9
10
def h_index(citations)
citations.sort!
h = 0
citations.reverse_each.with_index do |citation, i|
if citation >= i + 1
h = [h, i + 1].max
end
end
h
end

LeetCode 傳送門 - H-Index