其他分享
首页 > 其他分享> > 817.链表组件

817.链表组件

作者:互联网

 一、hash

 1 int numComponents(ListNode* head, vector<int>& G) {
 2     unordered_set<int> set(G.begin(), G.end());
 3     int res = 0;
 4     int len = 0;
 5     ListNode* temp = head;
 6     while (temp != nullptr)
 7     {
 8         int val = temp->val;
 9         if (set.find(val) != set.end())
10         {
11             if (len == 0)
12                 ++res;
13             ++len;
14         }
15         else
16         {
17             len = 0;
18         }
19         temp = temp->next;
20     }
21     return res;
22 }

二、暴力

 1 int numComponents(ListNode* head, vector<int>& G) {
 2     ListNode* temp = head;
 3     int res = 0;
 4     int len = 0;    
 5     while (temp != nullptr)
 6     {
 7         bool is_find = false;
 8         int val = temp->val;
 9         for (auto c : G)     //找这个数在不在G中
10         {
11             if (val == c)
12             {
13                 is_find = true;
14                 if (len==0)
15                 {
16                     ++res;
17                 }
18                 ++len;
19             }
20             if (is_find==true)
21                 break;
22         }
23         if (is_find == false)
24             len = 0;
25         temp = temp->next;
26     }
27     return res;
28 }

 

标签:val,temp,int,res,len,链表,组件,find,817
来源: https://www.cnblogs.com/zouma/p/11508329.html