Created
October 2, 2015 09:20
-
-
Save viveksyngh/9112ca7c6bd89fac97c5 to your computer and use it in GitHub Desktop.
Merge k sorted linked lists and return it as one sorted list.
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
| __author__ = 'Vivek' | |
| # Definition for singly-linked list. | |
| class ListNode: | |
| def __init__(self, x): | |
| self.val = x | |
| self.next = None | |
| import heapq | |
| class Solution: | |
| # @param A : list of linked list | |
| # @return the head node in the linked list | |
| def mergeKLists(self, A): | |
| if len(A) == 0 : | |
| return [] | |
| heap = [] | |
| res = ListNode(0) | |
| temp = res | |
| for i in range(len(A)) : | |
| if A[i] : | |
| heapq.heappush(heap,( A[i].val, i)) | |
| while heap : | |
| val, i = heapq.heappop(heap) | |
| temp.next = A[i] | |
| A[i] = A[i].next | |
| temp = temp.next | |
| if A[i] : | |
| heapq.heappush(heap, (A[i].val, i)) | |
| temp.next = None | |
| return res.next |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment