Skip to content

Conversation

@kazukiii
Copy link
Owner

問題へのリンク
https://leetcode.com/problems/kth-largest-element-in-a-stream/description/

次に解く問題
347. Top K Frequent Elements

README.mdへ頭の中の言語化と記録をしています。

- 最小ヒープを使う
- ヒープのサイズをkに保つ
- 初期化: O(n log k), 各クエリ: O(log k)
- fenwick tree上の二分探索(もしくはsegment tree上の二分探索)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(コードへのコメントではないですが。) fenwick tree 知らなかったので勉強になりました!

Comment on lines +5 to +9
for num in nums:
if len(self.num_min_heap) < k:
heapq.heappush(self.num_min_heap, num)
else:
heapq.heappushpop(self.num_min_heap, num)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

こちら、addを呼ぶといいと思います。

for num in nums:
    self.add(num)

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

気付きませんでした。シンプルになりますね。
ありがとうございます。

- kが各クエリで変わるときは、この方法になると思う(今回はk固定なのでスキップ)
- 初期化: O(n log n), 各クエリ: O(log n)
- 平衡二分探索木
- たぶん最終手段だと思う
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Python で使いたかったら、標準でないライブラリーがあります。C++ では標準で平衡木がありますね。

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

こちら調べてみました。

  • C++標準のmultisetを使うと、前から辿る必要があるので、kth elementをO(k)で取得可能
  • g++拡張の__gnu_pbdsにあるtreeを使うと、各ノードにsub treeのサイズを持たせられるオプションがあり、kth elemntをO(log n)で取得可能(LeetCodeでも使えました)
  • PythonでもLeetCodeで使えるものを探してみたところ、sortedcontainerのSortedListを使うとO(log n)でkth elementを取得できた

実装を追加してます。-> f382024

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants