美文网首页
Linked List Components

Linked List Components

作者: BLUE_fdf9 | 来源:发表于2018-09-29 23:52 被阅读0次

题目
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;
    }
}

相关文章

网友评论

      本文标题:Linked List Components

      本文链接:https://www.haomeiwen.com/subject/srdioftx.html