面试题 02.01. 移除重复节点
原始题目链接:https://leetcode-cn.com/problems/remove-duplicate-node-lcci/
编写代码,移除未排序链表中的重复节点。保留最开始出现的节点。
示例1:
输入:[1, 2, 3, 3, 2, 1]
输出:[1, 2, 3]
示例2:
输入:[1, 1, 1, 1, 2]
输出:[1, 2]
提示:
链表长度在[0, 20000]范围内。
链表元素在[0, 20000]范围内。
解题思路:
使用集合(哈希表)来判断是否存在相同的元素,单链表只有指向后继的节点,删除节点需要知道要删除节点的前驱节点,所以在遍历的时候有个小技巧,就是遍历前驱节点pre,符合删除条件然后直接使用pre.next = pre.next.next 删除当前节点即可,具体实现看代码。
代码实现:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeDuplicateNodes(self, head: ListNode) -> ListNode:
if not head:
return None
# 前驱节点
pre = head
uniq = {head.val}
while pre.next:
# 当前节点,判断是否需要删除
cur = pre.next
if cur.val not in uniq:
uniq.add(cur.val)
pre = pre.next
else:
pre.next = cur.next
return head