6
6
7
7
<p >We are given  ; <code >head</code >,  ; the head node of a linked list containing  ; <strong >unique integer values</strong >.</p >
8
8
9
-
10
-
11
9
<p >We are also given the list  ; <code >G</code >, a subset of the values in the linked list.</p >
12
10
13
-
14
-
15
11
<p >Return the number of connected components in <code >G</code >, where two values are connected if they appear consecutively in the linked list.</p >
16
12
17
-
18
-
19
13
<p ><strong >Example 1:</strong ></p >
20
14
21
-
22
-
23
15
<pre >
24
16
25
17
<strong >Input:</strong >
@@ -36,12 +28,8 @@ G = [0, 1, 3]
36
28
37
29
</pre >
38
30
39
-
40
-
41
31
<p ><strong >Example 2:</strong ></p >
42
32
43
-
44
-
45
33
<pre >
46
34
47
35
<strong >Input:</strong >
@@ -58,35 +46,77 @@ G = [0, 3, 1, 4]
58
46
59
47
</pre >
60
48
61
-
62
-
63
49
<p ><strong >Note: </strong ></p >
64
50
65
-
66
-
67
51
<ul >
68
52
<li>If <code>N</code> is the length of the linked list given by <code>head</code>, <code>1 <= N <= 10000</code>.</li>
69
53
<li>The value of each node in the linked list will be in the range<code> [0, N - 1]</code>.</li>
70
54
<li><code>1 <= G.length <= 10000</code>.</li>
71
55
<li><code>G</code> is a subset of all values in the linked list.</li>
72
56
</ul >
73
57
74
-
75
-
76
58
## Solutions
77
59
78
60
<!-- tabs:start -->
79
61
80
62
### ** Python3**
81
63
82
64
``` python
83
-
65
+ # Definition for singly-linked list.
66
+ # class ListNode:
67
+ # def __init__(self, val=0, next=None):
68
+ # self.val = val
69
+ # self.next = next
70
+ class Solution :
71
+ def numComponents (self , head : ListNode, nums : List[int ]) -> int :
72
+ s = set (nums)
73
+ res, pre = 0 , True
74
+ while head:
75
+ if head.val in s:
76
+ if pre:
77
+ res += 1
78
+ pre = False
79
+ else :
80
+ pre = True
81
+ head = head.next
82
+ return res
84
83
```
85
84
86
85
### ** Java**
87
86
88
87
``` java
89
-
88
+ /**
89
+ * Definition for singly-linked list.
90
+ * public class ListNode {
91
+ * int val;
92
+ * ListNode next;
93
+ * ListNode() {}
94
+ * ListNode(int val) { this.val = val; }
95
+ * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
96
+ * }
97
+ */
98
+ class Solution {
99
+ public int numComponents (ListNode head , int [] nums ) {
100
+ Set<Integer > s = new HashSet<> ();
101
+ for (int num : nums) {
102
+ s. add(num);
103
+ }
104
+ int res = 0 ;
105
+ boolean pre = true ;
106
+ while (head != null ) {
107
+ if (s. contains(head. val)) {
108
+ if (pre) {
109
+ ++ res;
110
+ pre = false ;
111
+ }
112
+ } else {
113
+ pre = true ;
114
+ }
115
+ head = head. next;
116
+ }
117
+ return res;
118
+ }
119
+ }
90
120
```
91
121
92
122
### ** ...**
0 commit comments