码迷,mamicode.com
首页 > 其他好文 > 详细

[Lintcode]98. Sort List/[Leetcode]148. Sort List

时间:2019-02-14 20:57:25      阅读:166      评论:0      收藏:0      [点我收藏+]

标签: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

标签:pac   leetcode   alter   dde   values   ace   复杂   ems   complex   

原文地址:https://www.cnblogs.com/siriusli/p/10376473.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!