Day 17
Date: October 12, 2022 12:50 PM
LinkedIn: https://leetcode.cn/problems/linked-list-components/
Title: 链表组件
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def numComponents(self, head: Optional[ListNode], nums: List[int]) -> int:
cur = head
n = 0
cnt = 0
while cur:
if cur.val in nums:# 顺序遍历cur中的数据在nums中
cnt += 1 # 标记满足组件条件
elif cnt > 0:
n += 1 # 计数组件
cnt = 0 #初始化
cur = cur.next
if cnt > 0: # 如果一直只标记没有计数直到循环结束
n += 1
return n