Created
February 20, 2026 11:28
-
-
Save GregoryMaks/4dc67b630871dbcb0d71a1b3fbf53920 to your computer and use it in GitHub Desktop.
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
| // Time: O(NxK) | |
| // Space: O(NxK) - need to store the results somewhere | |
| class Solution { | |
| func mergeKLists(_ lists: [ListNode?]) -> ListNode? { | |
| var tops = lists.compactMap { $0 ?? nil } | |
| var resultRoot: ListNode? | |
| var resultLast: ListNode? | |
| while tops.count > 0 { | |
| var pickIdx = 0 | |
| var val = Int.max | |
| // search | |
| for i in 0..<tops.count { | |
| if tops[i].val < val { | |
| pickIdx = i | |
| val = tops[i].val | |
| } | |
| } | |
| // save | |
| let newNode = ListNode(tops[pickIdx].val) | |
| if resultRoot != nil { | |
| resultLast?.next = newNode | |
| resultLast = newNode | |
| } else { | |
| resultRoot = newNode | |
| resultLast = newNode | |
| } | |
| // advance | |
| if let newTop = tops[pickIdx].next { | |
| tops[pickIdx] = newTop | |
| } else { | |
| tops.remove(at: pickIdx) | |
| } | |
| } | |
| return resultRoot | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment