LeetCode 817. 链表组件
原题链接
中等
作者:
autumn_0
,
2024-09-09 21:37:42
,
所有人可见
,
阅读 4
/**
* 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> numsSet = new HashSet<Integer>();
for(int num: nums) numsSet.add(num);
boolean inSet = false;
int res = 0;
while(head != null){
if(numsSet.contains(head.val)){
if(!inSet)
{
inSet = true;
res ++ ;
}
}
else{
inSet = false;
}
head = head.next;
}
return res;
}
}