- Leetcode 3217. Delete Nodes From Linked List Present in Array
- 1. 解题思路
- 2. 代码实现
- 题目链接:3217. Delete Nodes From Linked List Present in Array
1. 解题思路
这一题是一个十分典型的链表的问题,我们注意区分一下头节点和中间节点即可。
2. 代码实现
给出python代码实现如下:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:def modifiedList(self, nums: List[int], head: Optional[ListNode]) -> Optional[ListNode]:nums = set(nums)while head and head.val in nums:p = head.nexthead = pif head is None:return headpre, p = head, head.nextwhile p:while p and p.val in nums:pre.next = p.nextp = pre.nextif p:pre.next = ppre = pp = p.nextreturn head
提交代码评测得到:耗时708ms,占用内存55.1MB。