[LintCode 98] 链表排序(Python)
2017-09-19 17:45
756 查看
题目描述
在 O(n log n) 时间复杂度和常数级的空间复杂度下给链表排序。样例
给出 1->3->2->null,给它排序变成 1->2->3->null.
思路
归并法:找到链表的中点分治排序再归并。快排法:把头节点当做基准,分治为小于基准的链表,等于基准的链表和大于基准的链表。最后连起来。
代码
""" Definition of ListNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next """ class Solution: """ @param: head: The head of linked list. @return: You should return the head of the sorted linked list, using constant space complexity. """ # 归并法 def sortList1(self, head): # write your code here if head is None or head.next is None: return head pre = head slow = head fast = head while fast is not None and fast.next is not None: pre = slow slow = slow.next fast = fast.next.next pre.next = None return self.merge(self.sortList(head), self.sortList(slow)) def merge(self, l1, l2): if l1 is None: return l2 if l2 is None: return l1 if l1.val <= l2.val: l1.next = self.merge(l1.next, l2) return l1 else: l2.next = self.merge(l1, l2.next) return l2 # 快排法 def sortList2(self, head): # write your code here if head is None or head.next is None: return head pivot = head p = pivot l1 = ListNode(0) l2 = ListNode(0) s = l1 f = l2 tmp = head.next while tmp is not None: if tmp.val < pivot.val: s.next = tmp s = s.next elif tmp.val == pivot.val: p.next = tmp p = p.next else: f.next = tmp f = f.next tmp = tmp.next s.next = None f.next = None p.next = None l3 = self.sortList(l1.next) l4 = self.sortList(l2.next) if l3 is not None: l5 = l3 while l5.next is not None: l5 = l5.next l5.next = pivot p.next = l4 return l3 else: p.next = l4 return pivot
复杂度分析
时间复杂度O(nlogn),空间复杂度O(1)。相关文章推荐
- python_lintcode_115不同的路径 II_112删除排序链表中的重复元素
- [LintCode 104] 合并k个排序链表(Python)
- python_lintcode_93. 平衡二叉树_165. 合并两个排序链表_453. 将二叉树拆成链表
- LintCode 98-链表排序
- lintcode-98-链表排序
- lintcode 容易题 :Merge Two Sorted Lists合并两个排序链表
- lintcode,删除排序链表中的重复数字 II
- LintCode(M)删除排序链表中的重复数字 II
- python实现合并两个排序链表
- lintcode链表排序
- python_lintcode_372在O(1)时间复杂度删除链表节点_174删除链表中倒数第n个节点
- 删除排序链表中的重复元素-LintCode
- 合并两个排序的链表[剑指offer]之python实现
- Lintcode 合并两个排序的链表
- python_lintcode_64合并排序数组 II_60搜索插入位置_142 O(1)时间检测2的幂次
- [LintCode]112.删除排序链表中的重复元素
- LintCode : 合并两个排序链表
- LintCode-分治-合并k个排序链表
- Python 插入法实现链表排序
- lintcode,合并两个排序链表