日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

LeetCode 817. Linked List Components

發布時間:2025/3/20 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。