817. Linked List Components - LeetCode

Question

817. Linked List Components

Solution

题目大意:给一个链表和该链表元素组成的一个子数组,求子数组在链表中组成多少个片段,每个片段中可有多个连续的元素

思路:构造一个set用来存储子数组元素用于判断是否存在,遍历链表,如果当前元素不存在而下一个元素存在就表示一个片段的开始了,遍历前先判断首元素是否存在

Java实现:

public int numComponents(ListNode head, int[] G) {
    Set<Integer> existSet = new HashSet<>();
    for (int tmp : G) {
        existSet.add(tmp);
    }
    int ans = existSet.contains(head.val) ? 1 : 0;
    ListNode cur = head;
    while (cur.next != null) {
        if (!existSet.contains(cur.val) && existSet.contains(cur.next.val)) {
            ans++;
        }
        cur = cur.next;
    }
    return ans;
}

猜你喜欢

转载自www.cnblogs.com/okokabcd/p/9284926.html