[Lintcode]98. Sort List/[Leetcode]148. Sort List
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Lintcode]98. Sort List/[Leetcode]148. Sort List相关的知识,希望对你有一定的参考价值。
?????????pac leetcode alter dde values ace ?????? ems complex
98. Sort List/148. Sort List
- ????????????: Medium
- Topic: Linked List
Description
Sort a linked list in O(n log n) time using constant space complexity.
Example
Example 1:
Input: 1->3->2->null
Output: 1->2->3->null
Example 2:
Input: 1->7->2->6->null
Output: 1->2->6->7->null
Challenge
Solve it by merge sort & quick sort separately.
Challenge
Can you do this in-place without altering the nodes??? values?
????????????
class Solution(object):
def merge(self,x,y):
pos = ListNode(0)
res = pos
while(x and y):
if x.val<y.val:
pos.next = x
x = x.next
else:
pos.next = y
y = y.next
pos = pos.next
pos.next = x or y
return res.next
def sortList(self,head):
if not head or not head.next:
return head
pre,slow,fast = None, head,head
while fast and fast.next:
pre,slow,fast = slow,slow.next,fast.next.next
pre.next = None# ???????????????????????????????????????
return self.merge(*map(self.sortList,(head,slow)))
??????
??????????????????
- ??????????????? O(nlog(n))
以上是关于[Lintcode]98. Sort List/[Leetcode]148. Sort List的主要内容,如果未能解决你的问题,请参考以下文章
[LintCode] Insertion Sort List
[Lintcode]95. Validate Binary Search Tree/[Leetcode]98. Validate Binary Search Tree