-
Notifications
You must be signed in to change notification settings - Fork 0
/
h_index.cpp
74 lines (67 loc) · 1.59 KB
/
h_index.cpp
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/*
* =====================================================================================
*
* Filename: h_index.cpp
*
* Description: 274. H-Index. https://leetcode.com/problems/h-index/
*
* Version: 1.0
* Created: 01/14/2024 10:49:04
* Revision: none
* Compiler: gcc
*
* Author: [email protected]
* Organization:
*
* =====================================================================================
*/
#include <algorithm>
#include <utility>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using std::vector;
// std::sort
class Solution1 {
public:
int hIndex(vector<int>& citations) {
std::sort(citations.begin(), citations.end());
auto it = citations.rbegin();
int h = 0;
while (it != citations.rend()) {
if (*it++ <= h) {
break;
}
h++;
}
return h;
}
};
// Counting sort
class Solution2 {
public:
int hIndex(vector<int>& citations) {
const int n = citations.size();
vector<int> papers(n + 1);
for (const int val : citations) {
papers[std::min(val, n)]++;
}
int k = n;
for (int s = papers[n]; k > s; s += papers[k]) {
k--;
}
return k;
}
};
using Solution = Solution2;
TEST(Solution, hIndex) {
vector<std::pair<vector<int>, int>> cases = {
std::make_pair(vector<int>{3, 0, 6, 1, 5}, 3),
std::make_pair(vector<int>{1, 3, 1}, 1),
std::make_pair(vector<int>{13, 15}, 2),
std::make_pair(vector<int>{100}, 1),
};
for (auto& c : cases) {
EXPECT_EQ(Solution().hIndex(c.first), c.second);
}
}