zoukankan      html  css  js  c++  java
  • 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/

  • 相关阅读:
    WPF--常用布局介绍
    NUGET常用命令
    WPF 3D变换应用
    WPF MeshGeometry3D
    一组西门子S7 报文
    西门子与三菱PLC报文比较
    西门子S7报文解析
    C#与西门子PLC通讯
    Django之model admin自定义后台管理
    django ajax
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/11186769.html
Copyright © 2011-2022 走看看