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 }
原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/10971159.html