[LeetCode]82. 删除排序链表中的重复元素 II(Remove Duplicates from Sorted List II)

题目描述

给定一个排序链表,删除所有含有重复数字的节点,只保留原始链表中 没有重复出现 的数字。

示例 1:

输入: 1->2->3->3->4->4->5
输出: 1->2->5

示例 2:

输入: 1->1->1->2->3
输出: 2->3

解题思路

  1. 解法一:递归。
  2. 解法二:双指针。慢指针指向已完成部分的最后一个节点,快指针指向当前节点,并完全跳过重复的节点。

代码

Python 3.6

解法一:递归

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
if head is None or head.next is None:
return head
cur = head
repeat = False
while cur.next is not None and cur.val == cur.next.val:
repeat = True
cur = cur.next
if repeat:
return self.deleteDuplicates(cur.next)
else:
cur.next = self.deleteDuplicates(cur.next)
return cur

执行用时 : 56 ms
内存消耗 : 13.7 MB

解法二:双指针

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
if head is None or head.next is None:
return head
dummy = ListNode(head.val - 1)
dummy.next = head
slow = dummy
fast = dummy.next
while fast is not None:
if fast.next is not None and fast.val == fast.next.val:
tmp = fast.val
while fast is not None and fast.val == tmp:
fast = fast.next
else:
slow.next = fast
slow = slow.next
fast = fast.next
slow.next = fast
return dummy.next

执行用时 : 56 ms
内存消耗 : 13.7 MB

参考

https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list-ii/solution/kuai-man-zhi-zhen-by-powcai-2/