题目链接:https://leetcode.cn/problems/linked-list-components/description/
题目大意:给出一个vector<int> nums
,其中有一些数字。再给出一个链表的头指针head
,链表内的元素各不相同。如果链表中有某一段(长度大于等于1)的元素都在nums
中出现过,那么就算一个component,求链表中的component的个数。
思路:【判断是否在nums
中出现过】直接用set就好了,如果是STL的话,用count方法很方便。不过测试了一下后发现时间花得有点多,于是换成了数组。
使用两个布尔值:last
表示【上一个元素】【是否在nums
中出现过】,用flag
表示【当前元素】【是否在nums
中出现过】
- 当
last == false && flag == true
时,说明出现了一个新的component,结果加一 - 当
last == true && flag == false
时,说明出现了当前的component结束了 - 在判断之后都需要更新
last
完整代码
class Solution {
public:int numComponents(ListNode* head, vector<int>& nums) {bool nm[10001] = {0};for (auto x : nums) {nm[x] = true;}ListNode* ptr = head;bool last = false;int ret = 0;while (ptr) {bool flag = nm[ptr->val];if (flag != last) {if (last) {last = false;}else {ret++;last = true;}}ptr = ptr->next;}return ret;}
};