Sort a linked list in O(n log n) time using constant space complexity.

分析:题目要求时间复杂度为O(nlogn),所以不能用quickSort(最坏O(n^2)),可以使用mergeSort.

对一个链表进行归并排序,首先注意归并排序的基本思想:找到链表的middle节点,然后递归对前半部分和后半部分分别进行归并排序,最后对两个以排好序的链表进行Merge。

而找到链表中间点可以利用快慢指针的思想:用两个指针,一个每次走两步,一个走一步,知道快的走到了末尾,然后慢的所在位置就是中间位置,这样就分成了两个链表。

merge时,把两段头部节点值比较,用一个 p 指向较小的,且记录第一个节点,然后 两段的头一步一步向后走,p也一直向后走,总是指向较小节点,直至其中一个头为NULL,处理剩下的元素,最后返回记录的头节点即可。

code如下:

class Solution {
public:
ListNode *sortList(ListNode *head) {
if(!head||!head->next)
return head;
return mergeSort(head);
}
ListNode * mergeSort(ListNode *head){
if(!head||!head->next) //just one element
return head;
ListNode *p=head, *q=head, *pre=NULL;
while(q&&q->next!=NULL){
q=q->next->next;
pre=p;
p=p->next; //divide into two parts
}
pre->next=NULL;
ListNode *lhalf=mergeSort(head);
ListNode *rhalf=mergeSort(p); //recursive
return merge(lhalf, rhalf); //merge
}
ListNode * merge(ListNode *lh, ListNode *rh){
ListNode *temp=new ListNode(0);
ListNode *p=temp;
while(lh&&rh){
if(lh->val<=rh->val){
p->next=lh;
lh=lh->next;
}
else{
p->next=rh;
rh=rh->next;
}
p=p->next;
}
if(!lh)
p->next=rh;
else
p->next=lh;
p=temp->next;
temp->next=NULL;
delete temp;
return p;
}
};

python:

# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None class Solution(object):
def sortList(self, head):
if not head or not head.next:
return head
slow = head
fast = head.next

while fast and fast.next:
slow = slow.next
fast = fast.next.next rlist = self.sortList(slow.next)
slow.next = None
llist = self.sortList(head)
return self.mergeList(llist, rlist) def mergeList(self, l1, l2):
nHead = ListNode(0)
lastnode = nHead
while l1 and l2:
if l1.val < l2.val:
lastnode.next = l1
l1 = l1.next
else:
lastnode.next = l2
l2 = l2.next
lastnode = lastnode.next
lastnode.next = l1 or l2
return nHead.next

Python语言是一款对缩进非常敏感的语言,在编译时会出现这样的错IndentationError:expected an indented block说明此处需要缩进,你只要在出现错误的那一行,按空格或Tab(但不能混用)键缩进就行。 ----(有冒号的下一行往往要缩进,该缩进就缩进) 

ps:标记部分若set fast = head, the code will be beyond the time. The difference of the two situations are as follows:

 

leetcode:Sort List(一个链表的归并排序)的更多相关文章

  1. leetcode Sort List 对链表进行排序

    描述: Sort a linked list in O(n log n) time using constant space complexity. 在O(n*log(n))的时间复杂度,常数级空间复 ...

  2. [leetcode sort]148. Sort List

    Sort a linked list in O(n log n) time using constant space complexity. 以时间复杂度O(n log n)排序一个链表. 归并排序, ...

  3. leetcode菜鸡斗智斗勇系列(1)---把一个链表中的二进制数字转换为一个整型数(int)

    Convert Binary Number in a Linked List to Integer这道题在leetcode上面算作是“easy”,然而小生我还是不会做,于是根据大佬的回答来整理一下思路 ...

  4. [leetcode]Sort List @ Python

    原题地址:http://oj.leetcode.com/problems/sort-list/ 题意:链表的排序.要求:时间复杂度O(nlogn),空间复杂度O(1). 解题思路:由于题目对时间复杂度 ...

  5. LeetCode—-Sort List

    LeetCode--Sort List Question Sort a linked list in O(n log n) time using constant space complexity. ...

  6. LeetCode::Sort List 具体分析

    Sort a linked list in O(n log n) time using constant space complexity. 这道题目非常简短的一句话.给链表排序,看到nlogn.我们 ...

  7. C++:探究纯虚析构函数以及实现数组的高速排序与链表的归并排序

    C++:探究纯虚析构函数以及实现数组的高速排序与链表的归并排序 标签: 数据结构 数组 链表 高速排序 归并排序 抽象类 虚继承 by 小威威 1.介绍 本篇博文将通过课后作业的(15 C++ Hom ...

  8. leetcode23 多个拍好序的链表进行归并排序 (java版本)

    题目: Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexit ...

  9. [LeetCode] Linked List Components 链表组件

    We are given head, the head node of a linked list containing unique integer values. We are also give ...

随机推荐

  1. 【转载】C++编译出现 error C2664: 不能将参数 2 从“const char [5]”转换为“LPCTSTR”解决办法。

    编译程序的时候出现这样的错误,原因是在新建MFC项目的时候,设置字符集Unicode的属性. 解决方法一: 在VC2010的解决方案管理器窗口内,右击你的项目“项目”,然后选“属性”(最后一项),再点 ...

  2. Sencha Touch xtype对应的class

    Sencha Touch 2的有效xtype xtype Class ----------------- --------------------- actionsheet Ext.ActionShe ...

  3. LUCAS 定理

    原来一张图就就能证明:C(N,M)%P,p是素数. 简直太炫酷 先膜拜会 #include<iostream>#include<cstdio>#include<ctime ...

  4. Codeforces Round #231 (Div2) 迟到的解题报告

    题目A: 给一个火柴等式,可以从左边移动一根到右边,也可以从右边移到左边,但是不能移动“+”,”=“的火柴, 而且加法里面的数都要大于0(很重要的条件),基本上注意到这点的都过了,没注意的都被HACK ...

  5. Css选择器的优先级

    a = 行内样式style. b = ID选择器的数量. c = 类.伪类和属性选择器的数量. d = 类型选择器和伪元素选择器的数量. 选择器 等级(a,b,c,d) style=”” 1,0,0, ...

  6. Ogre1.8.1源码编译

    本文的编译环境为Windows7_SP1 + VS2010_SP1 + CMake2.8.11   :) 资源下载 1. 下载Ogre1.8.1的源代码,下载链接地址:http://www.ogre3 ...

  7. 【译】Python中如何创建mock?

    原文地址:http://engineroom.trackmaven.com/blog/making-a-mockery-of-python/ 今天我们来谈论下mock的使用.当然,请不要误会,这里的m ...

  8. DELPHI 获取本月 的第一天 和 最后一天

    USER :DateUtils 使用 StartOfTheMonth 和 EndOfTheMonth 函数获取即可:   procedure TForm1.btn1Click(Sender: TObj ...

  9. POJ 2724

    Purifying Machine Time Limit: 2000MS   Memory Limit: 65536K Total Submissions: 4014   Accepted: 1127 ...

  10. hdu 2639 Bone Collector II (01背包,求第k优解)

    这题和典型的01背包求最优解不同,是要求第k优解,所以,最直观的想法就是在01背包的基础上再增加一维表示第k大时的价值.具体思路见下面的参考链接,说的很详细 参考连接:http://laiba2004 ...