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?head,?1 <= 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
總結
以上是生活随笔為你收集整理的LeetCode 817. Linked List Components的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: DataFactory连接MySQL数据
- 下一篇: Python学习教程(Python学习路