24 leetcode - Merge k Sorted Lists

来源:互联网 发布:java物联网待遇 编辑:程序博客网 时间:2024/05/23 14:02
#!/usr/bin/python# -*- coding: utf-8 -*-'''英文:Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.中文:合并k个有序链表'''# Definition for singly-linked list.# class ListNode(object):#     def __init__(self, x):#         self.val = x#         self.next = None#如果新建节点的话,在字典中存储个数,而不是存储节点class Solution(object):    def mergeKLists(self, lists):        """        :type lists: List[ListNode]        :rtype: ListNode        """        #将空的去掉        index = 0        for val in lists:            if val:                lists[index] = val                index += 1        lists = lists[:index]          if not lists:            return []        #将所有节点遍历一次,存入字典中        d = {}        for i in range(len(lists)):            node = lists[i]            while node != None:                if d.has_key(node.val):                    d[node.val].append(node)                else:                    d[node.val] = [node]                node = node.next        #将键值排序,从小到大从字典中取值        l = d.keys()        l.sort()        start = node = d[l[0]].pop(0)        for i in l:            for j in d[i]:                start.next = j                start = start.next        start.next = None        return nodeif __name__ == "__main__":    s = Solution()    s.mergeKLists([[],[]])
0 0
原创粉丝点击