Skip to content

Latest commit

 

History

History
30 lines (28 loc) · 752 Bytes

817.md

File metadata and controls

30 lines (28 loc) · 752 Bytes

817. Linked List Components

Solution 1 (time O(n), space O(n))

# 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 numComponents(self, head, nums):
        """
        :type head: ListNode
        :type nums: List[int]
        :rtype: int
        """
        nums_set = set(nums)
        p = head
        flag = False
        ans = 0
        while p:
            if p.val in nums_set and not flag:
                flag = True
                ans += 1
            elif p.val not in nums_set:
                flag = False
            p = p.next
        return ans