LeetCode 817. Linked List Components (链表组件)

题目标签:Linked List

  题目给了我们一组 linked list, 和一组 G, 让我们找到 G 在 linked list 里有多少组相连的部分。

  把G 存入 hashset,遍历 linked list, 利用 hashset 来检查目前的点 和 下一个点 是否在G 里面。

  如果目前的点在G里面,下一个点不在,说明这里断开了。具体看code。

Java Solution:

Runtime:  7 ms, faster than 81 % 

Memory Usage: 40 MB, less than 93 %

完成日期:05/14/2019

关键点:HashSet

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public int numComponents(ListNode head, int[] G) {
        Set<Integer> set = new HashSet<>();
        int result = 0;
        
        for(int num : G) 
        {
            set.add(num);
        }
        
        for(ListNode node = head; node != null; node = node.next) 
        {
            if(set.contains(node.val) 
               && (node.next == null || !set.contains(node.next.val)))
                result++;
        }
     
        return result;
    }
}

参考资料:LeetCode Discuss

LeetCode 题目列表 - LeetCode Questions List

题目来源:https://leetcode.com/

原文地址:https://www.cnblogs.com/jimmycheng/p/11186769.html