Skip to content

Merge K Sorted Lists#122

Open
tom4649 wants to merge 3 commits into
mainfrom
23.Merge-k-Sorted-Lists
Open

Merge K Sorted Lists#122
tom4649 wants to merge 3 commits into
mainfrom
23.Merge-k-Sorted-Lists

Conversation

@tom4649
Copy link
Copy Markdown
Owner

@tom4649 tom4649 commented May 30, 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]
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

i は使われていないので不要そうです

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

indexを格納しないと、valが等しい場合、< が定義されずエラーが起こります。
コメントなどで補おうと思います。

node = dummy
while heap:
val, i, head = heapq.heappop(heap)
node.next = ListNode(val)
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

ここを

node.next = ListNode(head.val)

とすればヒープにvalを持たせる必要がなくなり、heap の要素を単に node だけにできると思います

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

ここも、 heap の要素が単に node だけでは順序比較ができないので、このような実装にしました。

二点のご指摘を受けて、ListNodeに__lt__メソッドを強制的に加えた実装を追加しました。
ListNodeの実装を変更できる状況であればこの実装がより自然だと思います。

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.

2 participants