LeetCode 148. Sort List 单链表排序 Python Solution
来源:互联网 发布:客观钓鱼岛主权 知乎 编辑:程序博客网 时间:2024/06/05 02:17
此题目对应于LeetCode 148
题目要求:
Sort a linked list in O(n log n) time using constant space complexity.
用O(n log n) 的排序算法,很容易让人想到用递推去做。
思路就是将单链表一分为二划分成两个子问题,然后递归调用算法,最后在做一个对两个
有序的单链表的合并操作(O(n))。
按照主定理:
T(n) = 2T(n/2) + n
则 T(n) = n = f(n), 则 T(n) = O(nlogn)
单链表一分为二就直接从单链表中间划分
下面附上python代码:
class ListNode: def __init__(self,x): self.val=x self.next=None def mergeTwoLists(self, l1, l2):#合并两个有序的链表 if not l1: return l2 if not l2: return l1 prenode = ListNode(1) p = prenode while l1 and l2: if l1.val <= l2.val: p.next = l1 l1 = l1.next else: p.next = l2 l2 = l2.next p = p.next if l1: p.next = l1 if l2: p.next = l2 return prenode.next def sortList(self, head): if not head or not head.next: return head prenode = head p1 = prenode p2 = prenode l = 0 while p1: l += 1 p1 = p1.next mid = l/2 k = 0 l1 = prenode while p2: # 将单链表从中间一分为二 if k >= mid-1: tmp = p2.next p2.next = None l2 = tmp break else: p2 = p2.next k += 1 t1 = self.sortList(l1) t2 = self.sortList(l2) return self.mergeTwoLists(t1,t2)
阅读全文
0 0
- LeetCode 148. Sort List 单链表排序 Python Solution
- [Leetcode Solution] Sort List
- [LeetCode] Sort List, Solution
- [Leetcode Solution]Insertion Sort List
- [LeetCode 148] Sort List Solution
- leetcode: Sort List, Merge sort solution. Java
- [leetcode] 【排序】 148. Sort List
- [leetcode-排序]--148. Sort List
- LeetCode-Sort List(Python)
- Sort List Leetcode Python
- Leetcode:Sort List 对单链表归并排序
- 【leetcode 单链表归并排序】Sort List
- 【LeetCode】 sort list 单链表的归并排序
- Leetcode 148 Sort List 单链表排序
- LeetCode Insertion Sort List(单链表插入排序)
- LeetCode Sort List(单链表归并排序)
- sort list leetcode (归并排序)
- LeetCode-Insertion Sort List (Python)
- dp-飞扬的小鸟
- ping过程中发生了什么
- eclipse里启动了tomcat正常,但是页面一直报404
- 初始mysql存储过程
- 爬取拉勾网招聘信息并使用xlwt存入Excel
- LeetCode 148. Sort List 单链表排序 Python Solution
- 设计模式系列-工厂模式
- Java多线程之自旋锁与队列锁
- 第十天总结
- 题目5:Binary String Matching
- What is REST
- windows环境搭建maven私服
- [BZOJ1041][HAOI2008]圆上的整点(数论)
- 解决Linux安装 VMware tools 工具的方法