• LeetCode 817. Linked List Components


    原题链接在这里:https://leetcode.com/problems/linked-list-components/

    题目:

    We are given head, the head node of a linked list containing unique integer values.

    We are also given the list G, a subset of the values in the linked list.

    Return the number of connected components in G, where two values are connected if they appear consecutively in the linked list.

    Example 1:

    Input: 
    head: 0->1->2->3
    G = [0, 1, 3]
    Output: 2
    Explanation: 
    0 and 1 are connected, so [0, 1] and [3] are the two connected components.
    

    Example 2:

    Input: 
    head: 0->1->2->3->4
    G = [0, 3, 1, 4]
    Output: 2
    Explanation: 
    0 and 1 are connected, 3 and 4 are connected, so [0, 1] and [3, 4] are the two connected components.
    

    Note:

    • If N is the length of the linked list given by head1 <= N <= 10000.
    • The value of each node in the linked list will be in the range [0, N - 1].
    • 1 <= G.length <= 10000.
    • G is a subset of all values in the linked list.

    题解:

    这道题是找connecteced components的组数. 如果有三组连着, e.g. [0,1], [3], [5]. 返回3.

    条件就是当前点的值在G中, next点不在G中, 或者为null.

    Time Complexity: O(n). n 是list长度.

    Space: O(m). m = G.length.

    AC Java:

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) { val = x; }
     7  * }
     8  */
     9 class Solution {
    10     public int numComponents(ListNode head, int[] G) {
    11         HashSet<Integer> hs = new HashSet<Integer>();
    12         for(int num : G){
    13             hs.add(num);
    14         }
    15         
    16         int res = 0;
    17         while(head != null){
    18             if(hs.contains(head.val) && (head.next == null || !hs.contains(head.next.val))){
    19                 res++;
    20             }
    21             
    22             head = head.next;
    23         }
    24         
    25         return res;
    26     }
    27 }
  • 相关阅读:
    高并发量网站解决方案
    多服务器之间Session共享
    Mysql性能优化
    PHP memcache的使用教程
    select * 为什么不好? limit 1 为什么好? --mysql SQL语句优化
    八大排序对比
    /var/spool/postfix/maildrop 出现大量文件原因和解决办法
    sql根据某一个字段重复只取第一条数据
    postgreSQL 自增需要使用序列
    MySQL锁定状态查看相关命令
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/10971159.html
Copyright © 2020-2023  润新知