【笔记】力扣 3217. 从链表中移除在数组中存在的节点——利用unordered_set集合提高查找效率

3217. 从链表中移除在数组中存在的节点

已解答

中等

提示

给你一个整数数组 nums 和一个链表的头节点 head。从链表中移除所有存在于 nums 中的节点后,返回修改后的链表的头节点。

示例 1:

输入: nums = [1,2,3], head = [1,2,3,4,5]

输出: [4,5]

解释:

img

移除数值为 1, 2 和 3 的节点。

示例 2:

输入: nums = [1], head = [1,2,1,2,1,2]

输出: [2,2,2]

解释:

img

移除数值为 1 的节点。

示例 3:

输入: nums = [5], head = [1,2,3,4]

输出: [1,2,3,4]

解释:

img

链表中不存在值为 5 的节点。

提示:

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 105
  • nums 中的所有元素都是唯一的。
  • 链表中的节点数在 [1, 105] 的范围内。
  • 1 <= Node.val <= 105
  • 输入保证链表中至少有一个值没有在 nums 中出现过。

题解

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
    // bool isFind(vector<int>& nums, int t) {
    //     for (int num:nums) {
    //         if (t==num) return true;
    //     }
    //     return false;
    // }
    // 线性查找频繁,时间效率低下
public:
    ListNode* modifiedList(vector<int>& nums, ListNode* head) {
        ListNode* p=head;
        ListNode* pre=head;
        unordered_set<int> myset(nums.begin(),nums.end());
        while (p!=nullptr) {
            if (myset.find(p->val)!=myset.end()) {
                if (p==pre) {
                    if (p->next==nullptr) head=nullptr;
                    else head=p->next;
                    pre=head;
                } else {
                    if (p->next==nullptr) pre->next=nullptr;
                    else pre->next=p->next;
                }
            } else {
                pre=p;
            }
            p=p->next;
        }
        return head;
    }
};
posted @ 2025-06-12 10:12  量子流浪猫  阅读(7)  评论(0)    收藏  举报