Conversation
| 手作業で考えてみる。 | ||
|
|
||
| とりあえず例として、 | ||
| > 10万枚くらいの大量のTシャツがあって、それぞれ番号が振られている。 |
There was a problem hiding this comment.
とりあえず、1人でもなんとかなる1000枚くらいで考えてみて、それから5人くらいでシフトを組むことを考えてみたらどうでしょうか。
| - heapにk個しかないなら、それでいいと思った。 | ||
| - vectorの添字アクセスしたくなかった。 | ||
| - emplace_backのほうが、push_backよりパフォーマンスがいいらしい。 | ||
| - https://morinokabu.com/2025/09/01/cpp-add-elements-to-container-emplace-back-insert/ |
There was a problem hiding this comment.
emplace_back と push_back の良し悪しは結構複雑です。
もしも、あまり考える気がないならば、push_back で統一しましょう。
そのパフォーマンスは move があれば数ナノ秒の話なのであまり気にしないで構いません。
その一方で、emplace_back はかなり複雑な事故を起こすことがあります。
中途半端な理解で使わないで欲しいものの代表格です。
There was a problem hiding this comment.
そうですね、しばらく調べて見たのですが自分にはなかなか複雑だったのでとりあえずはpush_backで統一しようと思います。
| auto comp = [&inventory](int n1, int n2) { | ||
| return inventory[n1] > inventory[n2]; | ||
| }; | ||
| priority_queue<int, vector<int>, decltype(comp)> heap(comp); |
There was a problem hiding this comment.
using P = pair<int, int>;
priority_queue<P, vector<P>, greater<P>> heap;とかでも良いのかなと思いました
There was a problem hiding this comment.
これだと、firstの値、つまり要素の種類で並び替えがかけられてしまうと思います。間違えていたらすみません!
https://cpprefjp.github.io/reference/utility/pair/op_less.html
There was a problem hiding this comment.
そうですね、この場合Pairの順序は頻度が先になるように並び変える必要があると思います。
| public: | ||
| vector<int> topKFrequent(vector<int>& nums, int k) { | ||
| if (k == nums.size()) return nums; | ||
| unordered_map<int, int> count_map; |
There was a problem hiding this comment.
unordered_map や map の変数名は、 XXX_to_YYY など、キーと値にどのようなものが含まれているかが分かりやすい名前にするとよいと思います。 num_to_count はいかがでしょうか?
| return count_map[n1] > count_map[n2]; | ||
| }; | ||
| priority_queue<int, vector<int>, decltype(comp)> heap(comp); | ||
| for (pair<int, int> p : count_map) { |
There was a problem hiding this comment.
念のため確認させてください。この部分は const 参照にすることもできますが、意図的に値型で受けたのでしょうか?
以下のコメントをご参照ください。
hemispherium/LeetCode_Arai60#10 (comment)
There was a problem hiding this comment.
いえ、特に意図的ではありませんでした。
強いていうと、参照だらけに感じたのと、特にコピーしても大して問題にならないのではと思いました。あまりにも感覚的な判断をしていました。
引用先を読んでおきます。
| auto comp = [&count_map](int n1, int n2) { | ||
| return count_map[n1] > count_map[n2]; | ||
| }; | ||
| priority_queue<int, vector<int>, decltype(comp)> heap(comp); |
There was a problem hiding this comment.
自分なら、変数にどのような値が含まれているか分かりやすいよう、 top_k_frequent_nums といった名前を付けると思います。
問題: https://leetcode.com/problems/top-k-frequent-elements/description/