forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sort-features-by-popularity.cpp
41 lines (39 loc) · 1.27 KB
/
sort-features-by-popularity.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
// Time: O(nlogn)
// Space: O(n)
class Solution {
public:
vector<string> sortFeatures(vector<string>& features, vector<string>& responses) {
unordered_set<string> features_set(cbegin(features), cend(features));
unordered_map<string, int> order;
for (int i = 0; i < size(features); ++i) {
order[features[i]] = i;
}
unordered_map<string, int> freq;
for (const auto&r : responses) {
const auto& words = split(r, ' ');
unordered_set<string> words_set(cbegin(words), cend(words));
for (const auto& word : words_set) {
if (features_set.count(word)) {
++freq[word];
}
}
}
sort(begin(features), end(features),
[&freq, &order](const auto& a, const auto& b) {
return pair(-freq[a], order[a]) < pair(-freq[b], order[b]);
});
return features;
}
private:
vector<string> split(const string& s, const char delim) {
vector<string> tokens;
stringstream ss(s);
string token;
while (getline(ss, token, delim)) {
if (!empty(token)) {
tokens.emplace_back(token);
}
}
return tokens;
}
};