Created
April 25, 2019 16:07
-
-
Save VladimirReshetnikov/18bdc76268e6f782adc2d1b05c4205a8 to your computer and use it in GitHub Desktop.
Top K Frequent Words
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://leetcode.com/problems/top-k-frequent-words | |
struct Solution final { | |
static vector<string> topKFrequent(vector<string>& words, int k) noexcept { | |
unordered_map<string, int> tally(words.size()); | |
auto it = words.begin(); | |
for (auto& w : words) if (!tally[w]--) swap(*it++, w); | |
words.resize(tally.size()); | |
const auto compare = [&tally](const string& a, const string& b) __attribute__((always_inline)) noexcept { | |
return tie(tally[a], a) < tie(tally[b], b); | |
}; | |
if (k == 1) { | |
iter_swap(words.begin(), min_element(words.begin(), words.end(), compare)); | |
words.resize(1); | |
return words; | |
} | |
nth_element(words.begin(), words.begin() + (k - 1), words.end(), compare); | |
words.resize(k); | |
sort(words.begin(), words.end(), compare); | |
return words; | |
} | |
}; | |
static const auto speedup = []() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); return 0; }(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment