题目
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.
答案
class Solution {
public int numComponents(ListNode head, int[] G) {
int[] map = new int[10000];
ListNode curr = head;
int num_components = 0;
for(int g : G) map[g] = 1;
boolean prev_in_map = false;
while(curr != null) {
boolean curr_in_map = map[curr.val] != 0;
if(!prev_in_map && curr_in_map) {
num_components++;
}
if(curr_in_map) prev_in_map = true;
else prev_in_map = false;
curr = curr.next;
}
return num_components;
}
}