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;
    }
}

参考资料:Le'e'tCode Discuss

LeetCode 题目列表 - LeetCode Questions List

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

转载于:https://www.cnblogs.com/jimmycheng/p/11186769.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值