Linked List Components

2018-09-29  本文已影响0人  BLUE_fdf9

题目
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;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读