【Leetcode】 817. Linked List Components

方法1

将G中的元素放入set 或者字典中用于查找。遍历链表, 链表中的元素被计数的条件是,如果当前元素在G中且下一个元素不在G中(或者为None),那么当前的元素属于一个component。

class Solution:
    def numComponents(self, head: ListNode, G: List[int]) -> int:
        set_G = set(G)
        p = head
        count =0
        while(p):
            if p.val in set_G and (p.next == None or p.next!=None and p.next.val not in set_G):
                count +=1
            p = p.next
        return count

方法2

当然也可以判断当前是否为不在G中下一个是否在G中,但是这样做得讨论一下特殊的情况 ,如果head.val不在G中,那么找到的count就是我们最总想要的count,如果head在G中,那么找到的count需要+1 。
x A x B和 A x B 的区别,这两个结果都是2,但是对于AxB,我们计算出的count =1

class Solution:
    def numComponents(self, head: ListNode, G: List[int]) -> int:
        set_G = set(G)
        count = 0
        p = head
        while(p):
            if p.val not in set_G and (p.next and p.next.val in set_G):
                count+=1
            p = p.next
        return count+1 if head.val in set_G else count

相关文章:

  • 2021-07-26
  • 2021-08-02
  • 2021-06-07
  • 2022-01-31
  • 2021-08-08
  • 2021-11-14
  • 2021-10-16
  • 2021-10-23
猜你喜欢
  • 2021-05-05
  • 2021-08-23
  • 2021-06-26
  • 2021-09-27
  • 2021-05-27
  • 2021-12-28
  • 2021-07-12
相关资源
相似解决方案