24 leetcode - Merge k Sorted Lists
2016-11-23 14:19
363 查看
#!/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 node if __name__ == "__main__": s = Solution() s.mergeKLists([[],[]])
相关文章推荐
- [leetcode 24] Merge Two Sorted Lists
- leetcode第21题-Merge Two Sorted Lists
- LeetCode 21. Merge Two Sorted Lists(C++版)
- 【leetcode】Merge k Sorted Lists
- [Leetcode] 21. Merge Two Sorted Lists
- LeetCode Merge k Sorted Lists
- [leetcode]Merge Two Sorted Lists
- 【Leetcode】Merge Two Sorted Lists in JAVA
- [LeetCode]21. Merge Two Sorted Lists
- Merge Two Sorted Lists leetcode java
- [Leetcode] 23. Merge k Sorted Lists
- Leetcode -- Merge k Sorted Lists
- leetcode 23. Merge k Sorted Lists
- 每周LeetCode算法题(四):Merge k Sorted Lists
- LeetCode - Merge Two Sorted Lists
- leetcode-Merge Two Sorted Lists
- 【leetcode】Merge k Sorted Lists
- leetcode第一刷_Merge k Sorted Lists
- leetcode-21-Merge Two Sorted Lists
- LeetCode 21 -- Merge Two Sorted Lists