Last active
February 13, 2020 18:49
-
-
Save onelharrison/fdc5de5685852a85286ed6b254253e52 to your computer and use it in GitHub Desktop.
Solution Video: https://www.youtube.com/watch?v=6bvnZzwiKzs
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
import heapq as heap | |
class HQNode: | |
def __init__(self, list_index, val_index, val): | |
self.list_index = list_index | |
self.val_index = val_index | |
self.val = val | |
def __eq__(self, other): | |
return self.val == other.val | |
def __gt__(self, other): | |
return self.val > other.val | |
def __ge__(self, other): | |
return self.val >= other.val | |
def __lt__(self, other): | |
return self.val < other.val | |
def __le__(self, other): | |
return self.val <= other.val | |
def merge_k_sorted_lists(sorted_lists): | |
'''Returns the merged, sorted results of the input list in O(kn log k) time''' | |
hq = [] | |
for i, sorted_list in enumerate(sorted_lists): | |
heap.heappush(hq, HQNode(i, 0, sorted_list[0])) | |
results = [] | |
while len(hq) != 0: | |
hq_node = heap.heappop(hq) | |
results.append(hq_node.val) | |
if hq_node.val_index + 1 < len(sorted_lists[hq_node.list_index]): | |
heap.heappush( | |
hq, | |
HQNode(hq_node.list_index, | |
hq_node.val_index + 1, | |
sorted_lists[hq_node.list_index][hq_node.val_index + 1]) | |
) | |
return results | |
print(merge_k_sorted_lists([[1, 2, 3, 20], [5, 6, 7, 14, 18], [4, 9, 10, 13, 15]])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment