817. Linked List Components

判断链表中元素是否在set(G)中得到连通分量的个数(下一个节点为null或者不在set中)。

public int numComponents(ListNode head, int[] G) {
    Set<Integer> set = new HashSet<Integer>();
    for (int i = 0; i < G.length; i++) {
        set.add(G[i]);
    }
    int res = 0;
    while (head != null) {
        if (set.contains(head.val) && (head.next == null || !set.contains(head.next.val))) {
            res++;
        }
        head = head.next;
    }
    return res;
}

results matching ""

    No results matching ""