Skip to content

Commit 0ec4e4e

Browse files
committed
83
1 parent b16296e commit 0ec4e4e

File tree

2 files changed

+87
-0
lines changed

2 files changed

+87
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -34,3 +34,4 @@ Success is like pregnancy, Everybody congratulates you but nobody knows how many
3434
| # | Title | Solution | Time | Space | Difficulty |Tag| Note|
3535
|-----|-------| -------- | ---- | ------|------------|---|-----|
3636
|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 | ||
37+
|148|[Sort List](https://leetcode.com/problems/sort-list/#/description)| [Python](./linkedlist/sortList.py) | _O(nlogn)_| _O(1)_ | Medium | ||

linkedlist/sortList.py

+86
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
# Author: Yu Zhou
2+
# 148. Sort List
3+
4+
# Sort a linked list in O(n log n) time using constant space complexity.
5+
6+
# 思路
7+
# 用链表的方式切分,然后递归Split,之后Merge
8+
# 这道题要注意是切分的时候,要写个Prev的函数用来储存Slow的原点
9+
10+
# Time: O(nlogn)
11+
# Space: O(1)
12+
13+
# ****************
14+
# Final Solution *
15+
# ****************
16+
class Solution(object):
17+
def sortList(self, head):
18+
if not head or not head.next:
19+
return head
20+
21+
prev = None
22+
fast = slow = head
23+
while fast and fast.next:
24+
prev = slow
25+
slow = slow.next
26+
fast = fast.next.next
27+
28+
mid = slow
29+
prev.next = None #截断
30+
31+
l = self.sortList(head) #递归
32+
r = self.sortList(mid)
33+
return self.merge(l, r)
34+
35+
36+
#这是一种类似于创建一个头的DummyNode,把Head设置成Prev,Cur设置成head.next
37+
def merge(self, l, r):
38+
guard = cur = ListNode(None)
39+
while l and r:
40+
if l.val <= r.val:
41+
cur.next = l
42+
l = l.next
43+
else:
44+
cur.next = r
45+
r = r.next
46+
cur = cur.next
47+
cur.next = l or r
48+
return guard.next
49+
50+
vhead = curr = ListNode(0)
51+
while l1 and l2:
52+
if l1.val <= l2.val:
53+
curr.next = l1
54+
l1 = l1.next
55+
else:
56+
curr.next = l2
57+
l2 = l2.next
58+
curr = curr.next
59+
curr.next = l1 or l2
60+
return vhead.next
61+
62+
63+
# ***************************************
64+
# The following code is an fail attempt *
65+
# ***************************************
66+
class Solution(object):
67+
def sortList(self, head):
68+
if not head or not head.next:
69+
return head
70+
71+
fast = slow = head
72+
#这里错在没有设置一个prev来保存Slow的值
73+
#每次while结束后,slow就会变成slow.next
74+
#假如想在slow的地方切断,就必须设置一个Prev
75+
#来保存slow的值,下方 mid = slow.next
76+
#其实已经是在经历过while 后的slow.next的next了
77+
while fast and fast.next:
78+
slow = slow.next
79+
fast = fast.next.next
80+
81+
mid = slow.next
82+
slow.next = None #截断
83+
84+
l = self.sortList(head) #递归
85+
r = self.sortList(mid)
86+
return self.merge(l, r)

0 commit comments

Comments
 (0)