-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy path82.remove-duplicates-from-sorted-list-ii.py
65 lines (57 loc) · 1.92 KB
/
82.remove-duplicates-from-sorted-list-ii.py
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#
# @lc app=leetcode id=82 lang=python3
#
# [82] Remove Duplicates from Sorted List II
#
# @lc code=start
# TAGS: Linked List
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
# Space O(N) would be easy
# 40 ms, 71.84%. Time: O(N). Space: O(1)
def deleteDuplicates(self, head: ListNode) -> ListNode:
if not head or not head.next: return head
duplicate = False
rv = dummy = ListNode(None)
node = head
while node and node.next:
if node.val == node.next.val:
duplicate = True
elif duplicate and node.val != node.next.val:
duplicate = False
elif not duplicate:
dummy.next = node
dummy = dummy.next
if not node.next.next and not duplicate:
dummy.next = node.next
dummy = dummy.next
node = node.next
dummy.next = None
return rv.next
# Article Solution
def deleteDuplicates(self, head: ListNode) -> ListNode:
# sentinel
sentinel = ListNode(0, head)
# predecessor = the last node
# before the sublist of duplicates
pred = sentinel
while head:
# if it's a beginning of duplicates sublist
# skip all duplicates
if head.next and head.val == head.next.val:
# move till the end of duplicates sublist
while head.next and head.val == head.next.val:
head = head.next
# skip all duplicates
pred.next = head.next
# otherwise, move predecessor
else:
pred = pred.next
# move forward
head = head.next
return sentinel.next
# @lc code=end