标定匹配list和对应的链表,首先可以把链表转化为线性表,考虑到Python的dict自带排序效果,引入有序字典OrderedDict,标记字典中已经在G中出现过的为1,未出现过的标记为0.
from collections import OrderedDict
class Solution:
def numComponents(self, head, G):
"""
:type head: ListNode
:type G: List[int]
:rtype: int
"""
dict1 = OrderedDict()
while head is not None:
dict1[head.val] = 0
head = head.next
for index in G:
dict1[index] = 1
isbreak = True #标记前一个是否是断开项
count = 0
for part in dict1.values():
if isbreak:
if part == 1:
count += 1
isbreak = False
else:
if part == 0:
isbreak = True
return count
#end def
897

被折叠的 条评论
为什么被折叠?



