๋์ด๋: Medium
ํค์๋: Hash Table
๐ฒ ๋ฌธ์
๋ฌธ์์ด ๋ฐฐ์ด words์ ์ ์ k๊ฐ ์ฃผ์ด์ก์ ๋, k๊ฐ์ ๊ฐ์ฅ ๋น๋ฒํ ๋ฌธ์์ด์ ๋ฐํํฉ๋๋ค.
๋น๋์๊ฐ ๋์ ์์๋๋ก ์ ๋ ฌ๋ ๋ต์ ๋ฐํํฉ๋๋ค. ๋์ผํ ๋น๋๋ฅผ ๊ฐ์ง ๋ฌธ์์ด์ ์ฌ์ ์์ผ๋ก ์ ๋ ฌํฉ๋๋ค.
๐ฒ ์์
Example 1:
Input: words = ["i","love","leetcode","i","love","coding"], k = 2
Output: ["i","love"]
Explanation: "i" and "love" are the two most frequent words.
Note that "i" comes before "love" due to a lower alphabetical order.
Example 2:
Input: words = ["the","day","is","sunny","the","the","the","sunny","is","is"], k = 4
Output: ["the","is","sunny","day"]
Explanation: "the", "is", "sunny" and "day" are the four most frequent words, with the number of occurrence being 4, 3, 2 and 1 respectively.
๐ฒ ๋ฌธ์ ํ์ด
hash๋ฅผ ์ฌ์ฉํด์ count๋ฅผ ํด์ฃผ๋ฉด ๋๋ ๋จ์ํ ๋ฌธ์ ์ด๋ค.
hash๋ฅผ ์ฌ์ฉํ count -> count ๊ฐ ๊ธฐ์ค์ผ๋ก sort -> ๊ทธ ์ค top-k๊ฐ๋ง ์ถ๋ ฅ ํ๋ฉด ๋๋๋ ๋ฌธ์ ์ด๋ค. (์ฝ์ฃ ?)
๋ฌธ์ ํ์ด ํ ๋, ๋ค์ํ ๋ฐ์ดํฐ ๊ตฌ์กฐ๋ฅผ ์จ๋ณด์ ์ถ์ด์ (python์ผ๋ก ์ฝ๋ฉ๋ฌธ์ ํ์ด๋ณด๋๊ฑฐ ์์ฆ cpp๋ก ์ฎ๊ฒจ๊ฐ๋ ์ค์ด๋ผ STL ์ตํ ๊ฒธ) ๊ตณ์ด ์์จ๋ ๋๋ heap์ ์จ๋ดค๋ค. ์ด ์ฝ๋์์ heap (priority_queue)๋ ์์จ๋ ๋๊ณ sorting ํ๋ ๊ฒ ์คํ๋ ค ๋ ๋ง๋ ์ฝ๋์ด๋ค. heap์ ๊ณ์ํด์ sorting์ด ํ์ํ ๋ ์ฌ์ฉํ๋ฉด ์ข์๋ฐ, ์ด ์ฝ๋์์๋ ์ฌ์ค์ ํ๋ฒ์ sortingํ๋ ๊ฑฐ๋ผ... ๊ทธ๋ค์ง ํจ์ฉ์ฑ์ ์๋ ์ฝ๋์ด๋ค.
compare ํจ์๋ฅผ ๋ฃ์ด์ค ๋ ์กฐ์ฌํ ์ ์, sort์ ๋ฃ์ด์ฃผ๋ compare๋ ํจ์๋ฅผ ์ ์ํด์ฃผ๋ฉด ๋์ง๋ง, heap ์ ๋ค์ด๊ฐ๋ compare ์ฉ ํจ์๋ compare class ๋ด์ operator() ๋ฅผ ์ค๋ฒ๋ผ์ด๋ฉํด์ฃผ๋ ํํ๋ก ์ ์ํด์ค์ผํ๋ค.
struct cmp{
bool operator()(pair<int, string> a, pair<int, string> b) const{
if(a.first > b.first)
return !(a.first > b.first);
if(a.first == b.first)
return !(a.second < b.second);
else
return !(false);
}
};
class Solution {
public:
vector<string> topKFrequent(vector<string>& words, int k) {
unordered_map<string, int> hash;
vector<string> ans;
// count
for(const auto word : words){
const auto ptr = hash.find(word);
if(ptr == hash.end())
hash[word] = 1;
else
hash[word] += 1;
}
// build heap
priority_queue<pair<int, string>, vector<pair<int, string>>, cmp> heap;
for(auto const& it: hash){
cout << it.first << " " << it.second << endl;
heap.push({it.second, it.first});
}
// find top k elements
for(auto _ = 0; _ < k; ++_){
ans.emplace_back(heap.top().second);
heap.pop();
}
return ans;
}
};
'IN DEPTH CAKE > Supercoder' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[c++/LeetCode-DP] 70. Climbing Stairs (1) | 2024.05.06 |
---|---|
[c++/LeetCode-Hash Table] 939. Minimum Area Rectangle (1) | 2024.05.05 |
[c++/LeetCode-Hash Table] 387. First Unique Character in a String (1) | 2024.05.05 |
[c++/LeetCode-Hash Table] 1. Two Sum (1) | 2024.05.05 |
[c++/LeetCode-Stack] 394. Decode String (1) | 2024.05.05 |