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. Beginners Guide To Learn Dimension Reduction Techniques

    Beginners Guide To Learn Dimension Reduction Techniques Introduction Brevity is the soul of wit This ...

  2. 如何快速查看将C反汇编的代码

    查看反汇编主要的思路在于将 流程,处理,算法 区分开来.1 函数调用:原C代码: int sum(int, int);int main(){ int c = sum(1, 2); printf(&qu ...

  3. MariaDB Galera Cluster 部署

    原文  http://code.oneapm.com/database/2015/07/02/mariadb-galera-cluster/MariaDB作为Mysql的一个分支,在开源项目中已经广泛 ...

  4. vi/vim使用指北 ---- Moving Around in a Hurry

    上一篇文章中,简单列出了一些基本的Vim操作,也列出了很多的光标移动命令,本章主要是有哪些命令可以更快的移动光标. vim的编辑操作,用得最多就是移动光标,对于很少行的文件来说,基本的命令就够用了,但 ...

  5. PC端模拟手机浏览网页

    很多网站都通过User-Agent来判断浏览器类型,如果是3G手机,显示手机页面内容,如果是普通浏览器,显示普通网页内容. 谷歌Chrome浏览器,可以很方便地用来当3G手机模拟器.在Windows的 ...

  6. iOS字符串大小转换

    NSString *test = @"Hello World";            // 小写      NSString *lower = [test lowercaseSt ...

  7. JMeter性能测试介绍学习一

    上一节中,我们了解了jmeter的一此主要元件,那么这些元件如何使用到性能测试中呢.这一节创建一个简单的测试计划来使用这些元件.该计划对应的测试需求. 1)测试目标网站是fnng.cnblogs.co ...

  8. ExtJs布局之accordion,fit,auto

    <!DOCTYPE html> <html> <head> <title>ExtJs</title> <meta http-equiv ...

  9. ExtJs之VTYPE验证

    <!DOCTYPE html> <html> <head> <title>ExtJs</title> <meta http-equiv ...

  10. C#的控制台程序输出

    1. int nChar; string mystring; Console.WriteLine("{0} {1}",nChar,mystring); 其中{0},{1}为占位符 ...