File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
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
+ };
You can’t perform that action at this time.
0 commit comments