[LeetCode] Linked List Components 鏈表組件

 

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

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

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:app

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:spa

  • 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.

 

這道題給了咱們一個鏈表,又給了咱們一個結點值數組,裏面不必定包括了鏈表中全部的結點值。讓咱們返回結點值數組中有多少個相連的組件,由於缺失的結點值會將原鏈表斷開,實際上就是讓咱們求有多少個相連的子鏈表,題目中給的例子很好的說明題意。這道題並不須要什麼特別高深的技巧,難懂的算法,直接按題目的要求來找就能夠了。首先,爲了快速的在結點值數組中查找某個結點值是否存在,咱們能夠將全部的結點值放到一個HashSet中,這樣咱們就能在常數級的時間複雜度中查找。而後咱們就能夠來遍歷鏈表了,對於遍歷到的每一個結點值,咱們只有兩種狀況,在或者不在HashSet中。不在HashSet中的狀況比較好辦,說明此時斷開了,而在HashSet中的結點,有多是該連續子鏈表的起始點,或者是中間的某個點,而咱們的計數器對該子鏈表只能自增1,因此咱們須要想辦法來hanlde這種狀況。博主最早想到的辦法是先處理不在HashSet中的結點,處理方法就是直接跳到下一個結點。那麼對於在HashSet中的結點,咱們首先將計數器res自增1,而後再來個循環,將以後全部在集合中的結點都遍歷完,這樣纔不會對同一個子鏈表屢次增長計數器,參見代碼以下:code

 

解法一:component

class Solution {
public:
    int numComponents(ListNode* head, vector<int>& G) {
        int res = 0;
        unordered_set<int> nodeSet(G.begin(), G.end());
        while (head) {
            if (!nodeSet.count(head->val)) {
                head = head->next;
                continue;
            }
            ++res;
            while (head && nodeSet.count(head->val)) {
                head = head->next;
            }
        }
        return res;
    }
};

 

咱們能夠稍稍修改代碼,使其更加簡潔,咱們在遍歷的時候進行判斷,若是當前結點在集合中,而且當前結點是尾結點或者下一個結點不在集合中的時候,咱們讓計數器自增1,經過這種操做,咱們不會多加也不會漏加計數器,參見代碼以下:htm

 

解法二:blog

class Solution {
public:
    int numComponents(ListNode* head, vector<int>& G) {
        int res = 0;
        unordered_set<int> nodeSet(G.begin(), G.end());
        while (head) {
            if (nodeSet.count(head->val) && (!head->next || !nodeSet.count(head->next->val))) {
                ++res;
            }
            head = head->next;
        }
        return res;
    }
};

 

參考資料:

https://leetcode.com/problems/linked-list-components/description/

https://leetcode.com/problems/linked-list-components/solution/

https://leetcode.com/problems/linked-list-components/discuss/123842/C++JavaPython-Easy-and-Concise-Solution-with-Explanation

 

LeetCode All in One 題目講解彙總(持續更新中...)

相關文章
相關標籤/搜索