-
Notifications
You must be signed in to change notification settings - Fork 0
703. Kth Largest Element in a Stream #8
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
Open
miyataka
wants to merge
1
commit into
main
Choose a base branch
from
703_KthLargestElementInAStream
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+260
−0
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,260 @@ | ||
| # 問題 | ||
| https://leetcode.com/problems/kth-largest-element-in-a-stream/description/ | ||
|
|
||
|
|
||
| # 前提 | ||
| - 答えを見ずに考えて、5分考えて分からなかったら答えを見てください。答えを見て理解したと思ったら、答えを隠して書いてください。筆が進まず5分迷ったら答えを見てください。そして、見ちゃったら一回全部消してやり直しです。答えを送信して、正解になったら、まずは一段階目です。 | ||
| - 次にコードを読みやすくするようにできるだけ整えましょう。これで動くコードになったら二段階目です。 | ||
| - そしたらまた全部消しましょう。今度は、時間を測りながら、もう一回、書きましょう。書いてアクセプトされたら文字を消してもう一回書きましょう。これを10分以内に一回もエラーを出さずに書ける状態になるまで続けてください。3回続けてそれができたらその問題はひとまず丸です。 | ||
| --- | ||
|
|
||
| # 1回目 | ||
|
|
||
| ```go | ||
| import "slices" | ||
|
|
||
| type KthLargest struct { | ||
| nums []int | ||
| nth int | ||
| } | ||
|
|
||
|
|
||
| func Constructor(k int, nums []int) KthLargest { | ||
| slices.SortFunc(nums, func(a, b int) int { | ||
| return b-a | ||
| }) | ||
| return KthLargest{ | ||
| nums, | ||
| k, | ||
| } | ||
| } | ||
|
|
||
|
|
||
| func (this *KthLargest) Add(val int) int { | ||
| arr := append(this.nums, val) | ||
| slices.SortFunc(arr, func(a, b int) int { | ||
| return b-a | ||
| }) | ||
| this.nums = arr | ||
| return arr[this.nth-1] | ||
| } | ||
| ``` | ||
| - 考え方: structに逆順ソート済みのsliceを持つ.`Add()`される度にsliceにappendして逆順ソートをやり直す.nthを返す. | ||
| - `slices.Sort()` では逆順にならんので,`slices.SortFunc`を調べた.なにも見ずにはかけない | ||
| - https://pkg.go.dev/slices#SortFunc | ||
| - 不安定ソート. 安定ソートは同じ順序ならそのオブジェクトの相対位置が保ったままになるかどうかの違い(という理解) | ||
| - 何度かfailさせた.numsの上書きを忘れたのと, return次の`nth-1`を`nth`にしてしまってた | ||
|
|
||
| # 2回目 | ||
|
|
||
| ```go | ||
| import "slices" | ||
|
|
||
| type KthLargest struct { | ||
| nums []int | ||
| nth int | ||
| } | ||
|
|
||
|
|
||
| func Constructor(k int, nums []int) KthLargest { | ||
| return KthLargest{ | ||
| nums, | ||
| k, | ||
| } | ||
| } | ||
|
|
||
|
|
||
| func (this *KthLargest) Add(val int) int { | ||
| arr := append(this.nums, val) | ||
| slices.SortFunc(arr, func(a, b int) int { | ||
| return b-a | ||
| }) | ||
| this.nums = arr | ||
| return arr[this.nth-1] | ||
| } | ||
|
|
||
| ``` | ||
| - Costructor時点でのSortFuncは無意味だなということで削除 | ||
| - あまり綺麗にならないし,性能も悪いようだ 1000ms以上かかっている | ||
|
|
||
| # 3回目 | ||
|
|
||
| ```go | ||
| import "slices" | ||
|
|
||
| type KthLargest struct { | ||
| nums []int | ||
| limit int | ||
| } | ||
|
|
||
|
|
||
| func Constructor(k int, nums []int) KthLargest { | ||
| slices.SortFunc(nums, func(a, b int) int { | ||
| return b-a | ||
| }) | ||
| return KthLargest{ | ||
| nums, | ||
| k, | ||
| } | ||
| } | ||
|
|
||
|
|
||
| func (this *KthLargest) Add(val int) int { | ||
| this.nums = append(this.nums, val) | ||
| slices.SortFunc(this.nums, func(a, b int) int { | ||
| return b-a | ||
| }) | ||
| this.nums = this.nums[:this.limit] | ||
| return this.nums[len(this.nums)-1] | ||
| } | ||
| ``` | ||
| - あまりに遅いので,他の人のコードを参照してみた | ||
| - https://github.com/n6o/leetcode_arai60/pull/8/changes | ||
| - 自分の実装がnumsを必要以上に保持する作りになっていたことを理解したので,その時点でのnthより後ろを捨てるように.そしてnthをlimitにリネーム | ||
| - 選択肢として以下がそれぞれあったことを理解した. | ||
| - インプットを全保持,降順でソート,nthを返す | ||
| - 上記の改良版として降順ソートしてn個だけ保持しておき,末尾を返す方針 | ||
| - 最初にソートして,末尾からn個分だけ保持する.その後はAddの度に2分探索を使って挿入位置を特定し,挿入する.この時点で昇順でn+1の長さになっているので,先頭から2番目(i=1)を返すと,大きい数値からn番目を返したことになる | ||
| - 最小ヒープを利用する方法(まだ理解はできていない) | ||
|
|
||
|
|
||
| # 4回目 | ||
|
|
||
| ## 都度降順ソート | ||
| ```go | ||
| import "slices" | ||
|
|
||
| type KthLargest struct { | ||
| nums []int | ||
| limit int | ||
| } | ||
|
|
||
|
|
||
| func Constructor(k int, nums []int) KthLargest { | ||
| localNums := nums | ||
| slices.SortFunc(localNums, func(a, b int) int { | ||
| return b-a | ||
| }) | ||
| if len(localNums) > k { | ||
| localNums = localNums[:k] | ||
| } | ||
|
|
||
| return KthLargest{ | ||
| nums: localNums, | ||
| limit: k, | ||
| } | ||
| } | ||
|
|
||
|
|
||
| func (this *KthLargest) Add(val int) int { | ||
| localNums := append(this.nums, val) | ||
| slices.SortFunc(localNums, func(a, b int) int { | ||
| return b-a | ||
| }) | ||
| if len(localNums) > this.limit { | ||
| this.nums = localNums[:this.limit] | ||
| } else { | ||
| this.nums = localNums | ||
| } | ||
| return this.nums[len(this.nums)-1] | ||
| } | ||
| ``` | ||
|
|
||
| ## 2分探索 | ||
| ```go | ||
| type KthLargest struct { | ||
| nums []int | ||
| limit int | ||
| } | ||
|
|
||
|
|
||
| func Constructor(k int, nums []int) KthLargest { | ||
| localNums := append([]int{}, nums...) | ||
| slices.Sort(localNums) | ||
| if k < len(localNums) { | ||
| localNums = localNums[len(localNums)-k:] | ||
| } | ||
|
|
||
| return KthLargest{ | ||
| nums: localNums, | ||
| limit: k, | ||
| } | ||
| } | ||
|
|
||
|
|
||
| func (this *KthLargest) Add(val int) int { | ||
| insertIndex, _ := slices.BinarySearch(this.nums, val) | ||
| this.nums = slices.Insert(this.nums, insertIndex, val) | ||
| if this.limit < len(this.nums) { | ||
| this.nums = this.nums[1:] | ||
| } | ||
| return this.nums[0] | ||
| } | ||
| ``` | ||
|
|
||
| ## 最小ヒープ | ||
| ```go | ||
| import "container/heap" | ||
|
|
||
| type IntMinHeap []int | ||
|
|
||
| func (h IntMinHeap) Len() int { | ||
| return len(h) | ||
| } | ||
|
|
||
| func (h IntMinHeap) Less(i, j int) bool { | ||
| return h[i] < h[j] | ||
| } | ||
|
|
||
| func (h IntMinHeap) Swap(i, j int) { | ||
| h[i], h[j] = h[j], h[i] | ||
| } | ||
|
|
||
| func (h *IntMinHeap) Push(x any) { | ||
| *h = append(*h, x.(int)) | ||
| } | ||
|
|
||
| func (h *IntMinHeap) Pop() any { | ||
| old := *h | ||
| n := len(old) | ||
| x := (*h)[n-1] | ||
| *h = (*h)[:n-1] | ||
| return x | ||
| } | ||
|
|
||
| type KthLargest struct { | ||
| topK *IntMinHeap | ||
| limit int | ||
| } | ||
|
|
||
|
|
||
| func Constructor(k int, nums []int) KthLargest { | ||
| topK := &IntMinHeap{} | ||
| heap.Init(topK) | ||
|
|
||
| for _, n := range nums { | ||
| heap.Push(topK, n) | ||
| if k < topK.Len() { | ||
| heap.Pop(topK) | ||
| } | ||
| } | ||
|
|
||
| return KthLargest{ | ||
| topK: topK, | ||
| limit: k, | ||
| } | ||
| } | ||
|
|
||
|
|
||
| func (this *KthLargest) Add(val int) int { | ||
| heap.Push(this.topK, val) | ||
| if this.limit < this.topK.Len() { | ||
| heap.Pop(this.topK) | ||
| } | ||
| return (*this.topK)[0] | ||
| } | ||
| ``` | ||
|
|
||
| - ゴールが「選択肢が見えていて,選べて,書けて,説明できる状態」なので,とりあえず3パターン全部を3回繰り返す | ||
| - 最小ヒープの使い所を初めて知った. | ||
| - 自分のヒープの理解は「完全にソートされているわけではない.ただし最小(あるいは最大)がとれることは保証されている.」というもの | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
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.
自分が仮にこの問題を面接官として出題するとしたら、ヒープまたは二分木等を用いて、各操作を 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.
コメントありがとうございます
この部分、今回の例で言うと 'container/heap' を使えることは期待するが、その内部実装を再現できることは期待しないという意味と理解しました(読んではおきます)
今後の練習でheapを実装の選択肢として挙げられるようにしていきます🫡
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.
少し語弊がありました。申し訳ありません。
ヒープについては、おおよそどのようなデータ構造で、どのような処理を行っているかは常識に含まれると思います。一方、コーディング面接のその場で書ききれることは期待しないと思います。
二分木 (正確には二分探索木) については、おおよそどのようなデータ構造で、どのような処理を行っているかは常識に含まれると思います。また、木を平衡させないと O(log n) で処理できないですとか、木を平衡させるにあたり、 ALV 木、赤黒木、といった亜種があり、それぞれおおよそどのようなことを行っているかは常識に含まれると思います。
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.
ありがとうございます
ヒープと二分木で常識の度合いが異なるということでしょうか
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.
ヒープと二分木に限らず、すべて度合いが異なるように思います。このあたりは、問題を解き進める際に、他の参加者のソースコードを読んだり、レビューコメントを読んでつかんでいくことをお勧めいたします。