题目描述:
给定链表头结点 head,该链表上的每个结点都有一个 唯一的整型值 。
同时给定列表 G,该列表是上述链表中整型值的一个子集。
返回列表 G 中组件的个数,这里对组件的定义为:链表中一段最长连续结点的值(该值必须在列表 G 中)构成的集合。
链接:https://leetcode-cn.com/problems/linked-list-components
代码实现:
/*** 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) {int result = 0;Set<Integer> set = new HashSet<Integer>();ListNode cur = head;for(int n:nums) {set.add(n);}while(cur != null) {if (set.contains(cur.val) &&// 同时判断了最后一个结点 以及 next不为null的情况(cur.next == null || !set.contains(cur.next.val))) {result++;}cur = cur.next;}return result;}}
