Skip to content

Commit b16296e

Browse files
committed
83
1 parent b674b83 commit b16296e

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

README.md

+6
Original file line numberDiff line numberDiff line change
@@ -28,3 +28,9 @@ Success is like pregnancy, Everybody congratulates you but nobody knows how many
2828
|328|[Odd Even Linked List](https://leetcode.com/problems/odd-even-linked-list/#/description)| [Python](./linkedlist/oddEvenList.py) | _O(n)_| _O(1)_ | Medium | ||
2929
|143|[Reorder List](https://leetcode.com/problems/reorder-list/#/description)| [Python](./linkedlist/reorder.py) | _O(n)_| _O(1)_ | Medium | ||
3030
|24|[Swap Nodes in Pairs](https://leetcode.com/problems/swap-nodes-in-pairs/#/solutions)| [Python](./linkedlist/swapPairs.py) | _O(n)_| _O(1)_ | Medium | |[Note](http://imgur.com/a/4G6ng)|
31+
32+
33+
## 4/15 Tasks (LinkedList Medium)
34+
| # | Title | Solution | Time | Space | Difficulty |Tag| Note|
35+
|-----|-------| -------- | ---- | ------|------------|---|-----|
36+
|83|[Remove Duplicates from Sorted List](https://leetcode.com/problems/remove-duplicates-from-sorted-list/#/description)| [Python](./linkedlist/deleteDuplicates.py) | _O(n)_| _O(1)_ | Easy | ||

linkedlist/deleteDuplicates.py

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
# Author: Yu Zhou
2+
# 83. Remove Duplicates from Sorted List
3+
4+
# Given a sorted linked list, delete all duplicates such that each element appear only once.
5+
#
6+
# For example,
7+
# Given 1->1->2, return 1->2.
8+
# Given 1->1->2->3->3, return 1->2->3.
9+
10+
# 思路,不需要删除这个Node,只需要将Pointer指向之后的一个Node就行
11+
# 中间有个容易出错的就是,不要每次While循环,自动位移当前的Pointer
12+
# 在比对完当前Node和后面的所有Node直到没有重复的时候
13+
# 再 cur = cur.next
14+
15+
# ****************
16+
# Final Solution *
17+
# ****************
18+
class Solution(object):
19+
def deleteDuplicates(self, head):
20+
"""
21+
:type head: ListNode
22+
:rtype: ListNode
23+
"""
24+
cur = head
25+
while cur and cur.next:
26+
if cur.val == cur.next.val:
27+
cur.next = cur.next.next
28+
else:
29+
cur = cur.next
30+
return head
31+
32+
# ***************************************
33+
# The following code is an fail attempt *
34+
# ***************************************
35+
class Solution(object):
36+
def deleteDuplicates(self, head):
37+
"""
38+
:type head: ListNode
39+
:rtype: ListNode
40+
"""
41+
cur = head
42+
43+
while cur and cur.next:
44+
if cur.val == cur.next.val:
45+
cur.next = cur.next.next
46+
#问题出在这里
47+
#cur不应该在每次比对以后直接位移,应该等没有
48+
#duplicate以后再位移,所以这里要加Else
49+
#不加的后果是,底下之中corner case会失败: [1,1,1]
50+
cur = cur.next
51+
return head

0 commit comments

Comments
 (0)