-
Notifications
You must be signed in to change notification settings - Fork 0
703. Kth Largest Element in a Stream #9
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
| - 最小ヒープを使う | ||
| - ヒープのサイズをkに保つ | ||
| - 初期化: O(n log k), 各クエリ: O(log k) | ||
| - fenwick tree上の二分探索(もしくはsegment tree上の二分探索) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
(コードへのコメントではないですが。) fenwick tree 知らなかったので勉強になりました!
| 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) |
There was a problem hiding this comment.
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)There was a problem hiding this comment.
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) | ||
| - 平衡二分探索木 | ||
| - たぶん最終手段だと思う |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Python で使いたかったら、標準でないライブラリーがあります。C++ では標準で平衡木がありますね。
There was a problem hiding this comment.
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を取得できた
- こちらは内部実装を確認したところおそらく平衡木ベースではなさそう
- https://grantjenks.com/docs/sortedcontainers/sortedlist.html
実装を追加してます。-> f382024
問題へのリンク
https://leetcode.com/problems/kth-largest-element-in-a-stream/description/
次に解く問題
347. Top K Frequent Elements
README.mdへ頭の中の言語化と記録をしています。