Skip to content

Commit 40b10d0

Browse files
authored
Create sort-features-by-popularity.cpp
1 parent 7ca1591 commit 40b10d0

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

C++/sort-features-by-popularity.cpp

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
// Time: O(nlogn)
2+
// Space: O(n)
3+
4+
class Solution {
5+
public:
6+
vector<string> sortFeatures(vector<string>& features, vector<string>& responses) {
7+
unordered_set<string> features_set(cbegin(features), cend(features));
8+
unordered_map<string, int> order;
9+
for (int i = 0; i < size(features); ++i) {
10+
order[features[i]] = i;
11+
}
12+
unordered_map<string, int> freq;
13+
for (const auto&r : responses) {
14+
const auto& words = split(r, ' ');
15+
unordered_set<string> words_set(cbegin(words), cend(words));
16+
for (const auto& word : words_set) {
17+
if (features_set.count(word)) {
18+
++freq[word];
19+
}
20+
}
21+
}
22+
sort(begin(features), end(features),
23+
[&freq, &order](const auto& a, const auto& b) {
24+
return pair(-freq[a], order[a]) < pair(-freq[b], order[b]);
25+
});
26+
return features;
27+
}
28+
29+
private:
30+
vector<string> split(const string& s, const char delim) {
31+
vector<string> tokens;
32+
stringstream ss(s);
33+
string token;
34+
while (getline(ss, token, delim)) {
35+
if (!empty(token)) {
36+
tokens.emplace_back(token);
37+
}
38+
}
39+
return tokens;
40+
}
41+
};

0 commit comments

Comments
 (0)