Merge K Sorted Lists#122
Open
tom4649 wants to merge 3 commits into
Open
Conversation
hroc135
reviewed
May 31, 2026
|
|
||
| class Solution: | ||
| def mergeKLists(self, lists: list[ListNode | None]) -> ListNode | None: | ||
| heap = [(node.val, i, node) for i, node in enumerate(lists) if node is not None] |
Owner
Author
There was a problem hiding this comment.
indexを格納しないと、valが等しい場合、< が定義されずエラーが起こります。
コメントなどで補おうと思います。
hroc135
reviewed
May 31, 2026
| node = dummy | ||
| while heap: | ||
| val, i, head = heapq.heappop(heap) | ||
| node.next = ListNode(val) |
There was a problem hiding this comment.
ここを
node.next = ListNode(head.val)とすればヒープにvalを持たせる必要がなくなり、heap の要素を単に node だけにできると思います
Owner
Author
There was a problem hiding this comment.
ここも、 heap の要素が単に node だけでは順序比較ができないので、このような実装にしました。
二点のご指摘を受けて、ListNodeに__lt__メソッドを強制的に加えた実装を追加しました。
ListNodeの実装を変更できる状況であればこの実装がより自然だと思います。
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
https://leetcode.com/problems/merge-k-sorted-lists/description/?envType=problem-list-v2&envId=rab78cw1