Skip to content

Commit 8ab50ac

Browse files
committed
leetcode82 提供更多的解法
1 parent ec09c8d commit 8ab50ac

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

leetcode/0082.Remove-Duplicates-from-Sorted-List-II/82. Remove Duplicates from Sorted List II.go

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,3 +91,66 @@ func deleteDuplicates(head *ListNode) *ListNode {
9191
}
9292
return head
9393
}
94+
95+
// 双循环简单解法 O(n*m)
96+
func deleteDuplicates3(head *ListNode) *ListNode {
97+
if head == nil {
98+
return head
99+
}
100+
101+
nilNode := &ListNode{Val: 0, Next: head}
102+
head = nilNode
103+
104+
lastVal := 0
105+
for head.Next != nil && head.Next.Next != nil {
106+
if head.Next.Val == head.Next.Next.Val {
107+
lastVal = head.Next.Val
108+
for head.Next != nil && lastVal == head.Next.Val {
109+
head.Next = head.Next.Next
110+
}
111+
} else {
112+
head = head.Next
113+
}
114+
}
115+
return nilNode.Next
116+
}
117+
118+
// 双指针+删除标志位,单循环解法 O(n)
119+
func deleteDuplicates4(head *ListNode) *ListNode {
120+
if head == nil || head.Next == nil {
121+
return head
122+
}
123+
124+
nilNode := &ListNode{Val: 0, Next: head}
125+
// 上次遍历有删除操作的标志位
126+
lastIsDel := false
127+
// 虚拟空结点
128+
head = nilNode
129+
// 前后指针用于判断
130+
pre, back := head.Next, head.Next.Next
131+
// 每次只删除前面的一个重复的元素,留一个用于下次遍历判重
132+
// pre, back 指针的更新位置和值比较重要和巧妙
133+
for head.Next != nil && head.Next.Next != nil {
134+
if pre.Val != back.Val && lastIsDel {
135+
head.Next = head.Next.Next
136+
pre, back = head.Next, head.Next.Next
137+
lastIsDel = false
138+
continue
139+
}
140+
141+
if pre.Val == back.Val {
142+
head.Next = head.Next.Next
143+
pre, back = head.Next, head.Next.Next
144+
lastIsDel = true
145+
} else {
146+
head = head.Next
147+
pre, back = head.Next, head.Next.Next
148+
lastIsDel = false
149+
}
150+
}
151+
// 处理 [1,1] 这种删除还剩一个的情况
152+
if lastIsDel && head.Next != nil {
153+
head.Next = nil
154+
}
155+
return nilNode.Next
156+
}

0 commit comments

Comments
 (0)