Linked list component
Question description
Given the head node of the linked list, each node on the linked list has a unique integer value. At the same time, the list nums is given, which is a subset of the integer values in the above linked list.
Returns the number of components in the list nums. The component is defined here as: the set of values of the longest continuous node in the linked list (the value must be in the list nums).
Example 1:
Input: head = [0,1,2,3], nums = [0,1,3]
Output: 2
Explanation: In the linked list, 0 and 1 are connected, and nums does not contain 2, so [0, 1] is a component of nums. Similarly, [3] is also a component, so 2 is returned.
Example 2:
Input: head = [0,1,2,3,4], nums = [0,3,1,4]
Output: 2
Explanation: In the linked list, 0 and 1 are connected, 3 and 4 are are connected, so [0, 1] and [3, 4] are two components, so 2 is returned.
Tip:
The number of nodes in the linked list is n
1 <= n <= 10^4
0 <= Node.val < n
All values in Node.val are different
1 <= nums.length <= n
0 <= nums[i] < n
All values in nums are different
HashSet simulation
Just simulate according to the meaning of the question: In order to easily determine whether a certain node.val exists in nums, we first use the Set structure to dump all nums[i], and then check the number of consecutive segments (components) each time .
Code demo:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public int numComponents(ListNode head, int[] nums) {
Set<Integer>set = new HashSet<>();
int count = 0;
//方便进行判断,如果用数组判断,那么每次都要循环,这个优化很重要。
for(int x : nums){
set.add(x);
}
while(head != null){
if(set.contains(head.val)){
while(head != null && set.contains(head.val)){
head = head.next;
}
count++;
}else{
head = head.next;
}
}
return count;
}
}