347.top k frequent elements#9
Conversation
| 参考:https://discord.com/channels/1084280443945353267/1235829049511903273/1245555256360697949 | ||
|
|
||
| 頻度の数え上げはmapでなくunordered_mapでおこなう。unordered_mapはハッシュマップなので時間計算量がO(N)で済む。対してmapは木構造でO(NlogM)。 | ||
| あと、priority_queueでgreater(昇順)にしたもの最小ヒープとよぶらしい。最小ヒープの要素数を減らしていくと自動的にk番目に行き着く。 |
There was a problem hiding this comment.
(こちらは、C++ の宣言の話をしているとは思いますが)
一応、wikipediaによるとmin-heap, max-heapの定義は以下のように書かれています。
In a max heap, for any given node C, if P is the parent node of C, then the key (the value) of P is greater than or equal to the key of C. In a min heap, the key of P is less than or equal to the key of C.
https://en.wikipedia.org/wiki/Heap_(data_structure)
There was a problem hiding this comment.
レビューありがとうございます。
なるほど、親が子より小さいだけでなく同じ場合も含むのですね。
| class Solution { | ||
| public: | ||
| vector<int> topKFrequent(vector<int>& nums, int k) { | ||
| map<int, int> mp; |
There was a problem hiding this comment.
mapはkeyとvalueに何が入っているかわかる名前が良いかと思います。
num_to_countsやnum_to_frequencyはいかがでしょうか。
There was a problem hiding this comment.
mapではkey_to_elementと名付けるのが一般的なのですね。参考にさせていただきます。
| 最後に、vector<int>を作ってmultimapの後ろから走査を行う。mapは昇順、つまり最初のイテレータに最小のキー、最後のイテレータに最大のキーが並ぶ。 | ||
| 出現回数の最も多い要素(値)をk個入れたvectorを返す。 | ||
|
|
||
| 計算量はgeminiによると空間計算量がO(M)で時間計算量がO(NlogM)になるらしい。Mはnumsのうちのユニークな要素数。 |
There was a problem hiding this comment.
Mというより、kといったほうが分かりやすいと思います。
また、こちらをご参考にしてみてください。
Yuto729/leetcode#16 (comment)
There was a problem hiding this comment.
ありがとうございます。
一応、ユニークな値の個数Mと指定されるkは異なることもあるという考えで書いています。
具体的に秒単位で求められる目安があるのですね。計算量が何を表しているのか分からなかったので参考になります。
追記:Mとkは同じです。kは最大で出現する数字の種類数と同じ値を取ります。
|
|
||
| 問題は | ||
| 1.vector<int>型の配列numsと整数kを与えられる。 | ||
| (ただし、kは最低1から最大でも「配列に一回のみ出現する値」の個数までしか取らない。例:[1,2,3,4,4]ならばkは1から3までしか取らない。) |
There was a problem hiding this comment.
レビューありがとうございます。
k is in the range [1, the number of unique elements in the array].
という記述について書いたつもりです。よろしければ誤読している箇所をお教えください。
There was a problem hiding this comment.
unique elements は、2つ以上あるものを削除ではなく1つだけ残したものということだろうと私は取りました。
There was a problem hiding this comment.
別の言い方をすると、len(set(nums))の意味ですね。
「配列に一回のみ出現する値」の個数だと、最初の例で矛盾していますし、文脈からも不自然だと思います。
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
There was a problem hiding this comment.
@oda @liquo-rice
ご返信ありがとうございます。
仰る通りですね。訂正しておきます。
| } | ||
| } | ||
| multimap<int, int> multi; | ||
| for (const auto& i:mp) { |
There was a problem hiding this comment.
(step2では修正されていますが)
Range-based for のコロンの前後はスペースをいれることが多いようですね。
https://google.github.io/styleguide/cppguide.html#Horizontal_Whitespace
このあたりもご覧になっていなければ、見てみてください。
https://github.com/takao-Tokunaga/leetcode/pull/1/changes#r3036658026
This problem: https://leetcode.com/problems/top-k-frequent-elements/
Next problem: https://leetcode.com/problems/find-k-pairs-with-smallest-sums/description/