题解 | #删除有序链表中重复的元素-II#
删除有序链表中重复的元素-II
https://www.nowcoder.com/practice/71cef9f8b5564579bf7ed93fbe0b2024
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param head ListNode类
# @return ListNode类
#
class Solution:
def deleteDuplicates(self , head: ListNode) -> ListNode:
# write code here
# 同样用集合的方法解决
if not(head):
return head
visit = {head.val}
this = head.next
# 记录出现过的数字
vnum = []
while this:
if this.val in visit:
vnum.append(this.val)
else:
visit.add(this.val)
this = this.next
# 删除重复出现的元素
# 找到第一个不重复的元素以此为头节点
this = head
while this:
if this.val in vnum:
this = this.next
else:
break
# 若全部都是重复的,则this == None
if not(this):
return this
# 找到第一个不重复元素,以此为头节点,并设置pre节点为this节点的前一个节点,方便后续删除节点
newhead = this
pre = newhead
this = this.next
# 开始删除元素
while this:
if this.val in vnum:
pre.next = this.next
this = this.next
else:
pre = this
this = this.next
# 返回新的头节点
return newhead
查看10道真题和解析