[英]Runtime Error - Merge k Sorted Lists on Leetcode
提示:本站为国内最大中英文翻译问答网站,提供中英文对照查看,鼠标放在中文字句上可显示英文原文。
任何人都可以帮助解决这个错误吗? 我不知道为什么它错了。 在执行“23. Merge k Sorted Lists”时,我不断收到运行时错误,但我的标准输出与预期一致。
Runtime Error
TypeError: [] is not valid value for the expected return type ListNode
raise TypeError(str(ret) + " is not valid value for the expected return type ListNode");
Line 65 in _driver (Solution.py)
_driver()
Line 71 in <module> (Solution.py)
这是我的代码:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
if not lists: return lists
if len(lists) == 1: return lists[0]
# return itself if 'lists' is empty or only has one ListNode
head = ListNode()
dummy_front = head
dummy_last = ListNode(10**5)
# During comparison, if a linkedlist is out of nodes, assign dummy_last to be its last node. The maximum value of a listnode is 10**4, so dummy_last would be the largest.*
flag = 0
# Use all_values to contain the current listnodes' values of all Linked lists. For example, with lists = [[1,4,5],[1,3,4],[2,6]], all_values = [1, 1, 2]
all_values = []
for i in range(0, len(lists)):
all_values.append(lists[i].val)
while True:
min_value = min(all_values)
if min_value == 10**5: break # Finished merging of all linked lists
min_index = all_values.index(min_value)
if flag == 0: # To decide if it's the first node of our answer linked list to assign the "head"
head.next = lists[min_index]
dummy_front = lists[min_index]
flag = 1
else:
dummy_front.next = lists[min_index]
dummy_front = dummy_front.next
all_values.pop(min_index) # Pop the used smallest value
if not lists[min_index].next: # If the linked list has no other nodes, assign dummy_last to be its last node.
lists[min_index] = dummy_last
else:
lists[min_index] = lists[min_index].next
all_values.insert(min_index, lists[min_index].val) # Insert new value at min_index
return head.next
Leetcode 提供了一个例子:
Input: lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]
Explanation: The linked-lists are:
[
1->4->5,
1->3->4,
2->6
]
merging them into one sorted list:
1->1->2->3->4->4->5->6
我的代码 output 是ListNode{val: 1, next: ListNode{val: 1, next: ListNode{val: 2, next: ListNode{val: 3, next: ListNode{val: 4, next: ListNode{val: 4, next: ListNode{val: 5, next: ListNode{val: 6, next: None}}}}}}}}
,这是正确的答案。 请帮忙! 非常感谢!!!!
您使这件事变得比必要的复杂得多。
只需构建一个包含所有 ListNode 的所有值的列表。 然后对该列表进行排序,然后构建一个单链表。
class Solution:
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
vals = []
for node in lists:
while node:
vals.append(node.val)
node = node.next
if not vals:
return
vals.sort()
result = ListNode(vals[0])
prev = result
for v in vals[1:]:
prev.next = ListNode(v)
prev = prev.next
return result
意识到 LeetCode 运行 3 个测试用例,因此错误可能在这三个中的任何一个中触发,不一定在您验证 output 的那个。
当以下if
条件为真时,会发生错误:
if not lists: return lists
在这种情况下lists
是一个空列表,但它仍然是一个列表,您将其返回。 这是不正确的,因为您应该返回ListNode
或None
。 在这种情况下,您应该返回None
。
应用此修复程序后,您将在这部分代码中遇到另一个问题:
for i in range(0, len(lists)):
all_values.append(lists[i].val)
lists[i]
可能是None
(表示一个空链表),在这种情况下lists[i].val
是一个无效引用。 为避免这种情况,您最好先从lists
删除所有空列表,就在 function 的顶部:
lists = list(filter(None, lists))
更正后,您会发现您的算法太慢而无法通过测试。 性能不佳的主要原因是这些说明:
min_value = min(all_values)
和:
min_index = all_values.index(min_value)
这将在每次迭代中发生,并且由于可能有多达 10000 个列表,这将影响性能。
要解决性能问题,您可以实施分而治之算法:只要您有len(lists) > 2
,将其分成两半并解决这两半的问题。 您将得到两个合并的列表,然后您必须合并它们。 这样你只需要实现合并两个列表的逻辑和分而治之的逻辑。
这是一个实现:
def mergeTwoLists(list1, list2):
result = prehead = ListNode()
while list1 and list2:
if list1.val < list2.val:
result.next = list1
list1 = list1.next
else:
result.next = list2
list2 = list2.next
result = result.next
result.next = list1 or list2
return prehead.next
def mergeLists(lists):
if len(lists) <= 2: # base case of recursion
return lists[0] if len(lists) == 1 else mergeTwoLists(*lists)
mid = len(lists) // 2
return mergeTwoLists(mergeLists(lists[:mid]), mergeLists(lists[mid:]))
class Solution:
def mergeKLists(self, lists):
if lists:
return mergeLists(lists)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.