【LEETCODE】148- Sort List [Python]
来源:互联网 发布:僵尸新娘 配乐 知乎 编辑:程序博客网 时间:2024/04/27 14:30
Sort a linked list in O(n log n) time using constant space complexity.
题意:
对一个链表排序,O(n log n) time , constant space complexity
思路:
根据题意对时间和空间复杂度的要求,此处排序用归并
参考:
归并排序:
http://blog.csdn.net/littlethunder/article/details/9472301
http://bookshadow.com/weblog/2014/11/21/leetcode-sort-list/
Python
# Definition for singly-linked list.# class ListNode(object):# def __init__(self, x):# self.val = x# self.next = Noneclass Solution(object): def sortList(self, head): """ :type head: ListNode :rtype: ListNode """ if head is None or head.next is None: return head mid=self.getmiddle(head) lHead=head rHead=mid.next mid.next=None return self.merge(self.sortList(lHead),self.sortList(rHead)) def getmiddle(self,head): if head is None: return head fast=slow=head while fast.next and fast.next.next: slow=slow.next fast=fast.next.next return slow def merge(self,lHead,rHead): dumNode=ListNode(0) dumHead=dumNode i=lHead j=rHead while i and j: if i.val<j.val: dumNode.next=i i=i.next else: dumNode.next=j j=j.next dumNode=dumNode.next if i: dumNode.next=i if j: dumNode.next=j return dumHead.next
0 0
- 【LEETCODE】148- Sort List [Python]
- [python]leetcode(148). Sort List
- LeetCode-Sort List(Python)
- Sort List Leetcode Python
- LeetCode-Insertion Sort List (Python)
- 【leetcode】sort list(python)
- [leetcode] Insertion Sort List(python)
- 【LeetCode with Python】 Sort List
- Insertion Sort List Leetcode Python
- [Leetcode][python]Insertion Sort List
- LeetCode(148)Sort List
- LeetCode: Sort List [148]
- LeetCode 148 Sort List
- [leetcode 148] Sort List
- [LeetCode 148]Sort List
- leetcode-148 Sort List
- Leetcode 148 Sort List
- LeetCode 148: Sort List
- VFW 介绍
- 【CSS3】:enabled选择器
- js 删除append标签添加的元素
- 易联云打印资料整理
- Android更新UI的2种方法
- 【LEETCODE】148- Sort List [Python]
- 海思3520D芯片硬盘和SD卡挂载说明
- 浅谈 Excel 对象模型
- Unity3D学习笔记(十)物理引擎:碰撞器
- 也议MySQL中隐式转换
- 【CSS3】:disabled选择器
- web Service入门实例
- 关于ARP的那些事儿
- Activity详解 (五) : startActivityForResult()与onActivityResult()