1. 题目原址
https://leetcode.com/problems/linked-list-components/
2. 题目描述
3. 题目大意
给定一个链表,和一个数组,返回数组将链表分割为几段。
4. 解题思路
- 首先将给定的数组放到一个Set集合中
- 如果链表的当前值在数组中,就将链表往前移动,一直移动到链表的当前值不在数组中
- 将返回值ret ++ ,然后将temp ++ . temp 表示当前链表中以及之前的元素是否在数组中。
- 最后还要判断head链表是否为空,因为如果链表中的当前元素不在数组中,链表也是需要向前移动的
5. AC代码
class Solution {
public int numComponents(ListNode head, int[] G) {
int temp = 0,ret = 0;
Set<Integer> set = new HashSet<Integer>();
for(int i: G) set.add(i);
while(head != null) {
while(head != null && set.contains(head.val)) {
head = head.next;
temp ++;
}
if(temp > 0) {
temp = 0;
ret ++;
}
if(head != null) head = head.next;
}
return ret;
}
}