LeetCode 分类刷题:3217. 从链表中移除在数组中存在的节点
题目
给你一个整数数组 nums 和一个链表的头节点 head。从链表中移除所有存在于 nums 中的节点后,返回修改后的链表的头节点。

解析
对于本题,由于直接判断节点值是否在 nums 中,需要遍历 nums,时间复杂度为 O(n)。把 nums 中的元素保存一个哈希集合中,然后判断节点值是否在哈希集合中,这样可以做到 O(1)。
具体做法:
- 把 nums 中的元素保存到一个哈希集合中。
- 由于头节点可能会被删除,在头节点前面插入一个哨兵节点 dummy,以简化代码逻辑。
- 初始化 cur=dummy。
- 遍历链表,如果 cur 的下一个节点的值在哈希集合中,则需要删除,更新 cur.next 为 cur.next.next;否则不删除,更新 cur 为 cur.next。
- 循环结束后,返回 dummy.next。
作者:灵茶山艾府
链接:https://leetcode.cn/problems/delete-nodes-from-linked-list-present-in-array/solutions/2843071/shao-bing-jie-dian-yi-ci-bian-li-pythonj-imre/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
答案
var modifiedList = function(nums, head) {const set = new Set(nums);const dummy = new ListNode(0, head);let cur = dummy;while (cur.next) {const nxt = cur.next;if (set.has(nxt.val)) {cur.next = nxt.next; // 从链表中删除 nxt 节点} else {cur = nxt; // 不删除 nxt,继续向后遍历链表}}return dummy.next;
};// 作者:灵茶山艾府
// 链接:https://leetcode.cn/problems/delete-nodes-from-linked-list-present-in-array/solutions/2843071/shao-bing-jie-dian-yi-ci-bian-li-pythonj-imre/
// 来源:力扣(LeetCode)
// 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。复杂度分析
时间复杂度:O(n+m),其中 n 是 nums 的长度,m 是链表的长度。
空间复杂度:O(n)。
具体分析
创建 Set:
new Set(nums)- 这是 O(n)遍历链表:
while (cur.next)- 这是 O(m)Set 查询:
set.has(nxt.val)- 每次都是 O(1)
