LeetCode - 148-- sort list (python)

Complexity and the spatial complexity of constant grade, are sorted linked list in O (n log n) time.

Example 1:

Input: 4-> 2-> 1-> 3
Output: 1-> 2-> 3-> 4
Example 2:

Input: -1-> 5-> 3-> 4-> 0
Output: -1-> 0-> 3-> 4-> 5

 

Insertion sort, certainly timed out, the worst time complexity is O (n ^ 2)

 1 class Solution:
 2     def sortList(self, head: ListNode) -> ListNode:
 3         if head==None or head.next==None:
 4             return head
 5         dummyY=ListNode(0)
 6         dummyY.next=head
 7         p = head
 8         r = p.next
 9         p.next=None
10         p=r
11         while p != None:
12             pre = dummyY
13             r = p.next
14             while pre.next!=None and pre.next.val <p.val:
15                 pre = pre.next
16             p.next = pre.next
17             pre.next = p
18             p = r            
19         return dummyY.next

 Merger

 1 class Solution:
 2     def sortList(self, head: ListNode) -> ListNode:
 3         if not head or not head.next:return head
 4         slow,fast = head,head.next
 5         while fast and fast.next:
 6             fast,slow=fast.next.next,slow.next
 7         mid,slow.next=slow.next,None
 8         left,right=self.sortList(head),self.sortList(mid)
 9         
10         h=res = ListNode(0)
11         while left and right:
12             if left.val < right.val :h.next,left=left,left.next
13             else:h.next,right=right,right.next
14             h=h.next
15         h.next=left if left else right
16         return res.next

 

Guess you like

Origin www.cnblogs.com/NPC-assange/p/11650237.html