Sort List

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

使用Merge Sort, 空间复杂度是 O(logN) 因为使用了栈空间。

SOLUTION 1:

使用Merge Sort来解决问题。

为什么不用QuickSort?
因为随机访问对于链表而言太耗时,而heap sort不可行。

注意,Find Mid用了2种解法。或者是让Fast提前结束,或是让Fast先走一步,目的就是要取得中间节点的前一个。这样做的目的,主要

是为了解决:

1->2->null

这一种情况。如果不这么做,slow会返回2.这样我们没办法切割2个Node的这种情况。

 /**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode sortList(ListNode head) {
// Nodes should be more than 2.
if (head == null || head.next == null) {
return head;
} // get the mid node.
ListNode midPre = getMidPre(head); // Cut the two list.
ListNode right = midPre.next;
midPre.next = null; // Sort the left side and the right side.
ListNode left = sortList(head);
right = sortList(right); // Merge the two sides together.
return merge(left, right);
} // get the pre node before mid.
public ListNode getMidPre1(ListNode head) {
ListNode slow = head;
ListNode fast = head; while (fast != null && fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
} return slow;
} // get the pre node before mid.
public ListNode getMidPre(ListNode head) {
ListNode slow = head; // fast提前一点儿。这样就可以得到前一个节点喽。
ListNode fast = head.next; while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
} return slow;
} public ListNode merge(ListNode head1, ListNode head2) {
ListNode dummy = new ListNode(0);
ListNode cur = dummy; while (head1 != null && head2 != null) {
if (head1.val < head2.val) {
cur.next = head1;
head1 = head1.next;
} else {
cur.next = head2;
head2 = head2.next;
} cur = cur.next;
} if (head1 != null) {
cur.next = head1;
} else {
cur.next = head2;
} return dummy.next;
}
}

SOLUTION 2:

使用快排也可以解决。但是注意,要加一个优化才可以过大数据,就是判断一下是不是整个链条是相同的节点,比如2 2 2 2 2 2 2 ,这样的就直接扫一次不用执行

快排,否则它会是N平方的复杂度。

参考资料:

https://oj.leetcode.com/discuss/3577/i-use-quick-sort-to-sort-the-list-but-why-i-get-time-limited

 /*
The Solution 2:
Quick Sort.
*/
public ListNode sortList(ListNode head) {
if (head == null) {
return null;
} // Sort the list from 0 to len - 1
return quickSort(head);
} // The quick sort algorithm // All the elements are the same!
public boolean isDuplicate(ListNode head) {
while (head != null) {
if (head.next != null && head.next.val != head.val) {
return false;
} head = head.next;
} return true;
} public ListNode quickSort(ListNode head) {
if (head == null) {
return null;
} // 如果整个链是重复的,直接跳过。
if (isDuplicate(head)) {
return head;
} // Use the head node to be the pivot.
ListNode headNew = partition(head, head.val); // Find the pre position of the pivoit.
ListNode cur = headNew; ListNode dummy = new ListNode(0);
dummy.next = headNew; ListNode pre = dummy; // Find the pre node and the position of the piviot.
while (cur != null) {
if (cur.val == head.val) {
break;
} // move forward.
cur = cur.next;
pre = pre.next;
} // Cut the link to be three parts.
pre.next = null; // Get the left link;
ListNode left = dummy.next; // Get the right link.
ListNode right = cur.next;
cur.next = null; // Recurtion to call quick sort to sort left and right link.
left = quickSort(left);
right = quickSort(right); // Link the three part together. // Link the first part and the 2nd part.
if (left != null) {
dummy.next = left; // Find the tail of the left link.
while (left.next != null) {
left = left.next;
}
left.next = cur;
} else {
dummy.next = cur;
} cur.next = right; // The new head;
return dummy.next;
} // Return the new head;
public ListNode partition(ListNode head, int x) {
if (head == null) {
return null;
} ListNode dummy = new ListNode(0);
dummy.next = head; ListNode pre = dummy;
ListNode cur = head; // Record the big list.
ListNode bigDummy = new ListNode(0);
ListNode bigTail = bigDummy; while (cur != null) {
if (cur.val >= x) {
// Unlink the cur;
pre.next = cur.next; // Add the cur to the tail of the new link.
bigTail.next = cur;
cur.next = null; // Refresh the bigTail.
bigTail = cur; // 移除了一个元素的时候,pre不需要修改,因为cur已经移动到下一个位置了。
} else {
pre = pre.next;
} cur = pre.next;
} // Link the Big linklist to the smaller one.
pre.next = bigDummy.next; return dummy.next;
}

GITHUB:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/list/SortList.java

LeetCode: Sort List 解题报告的更多相关文章

  1. LeetCode: Sort Colors 解题报告

    Sort ColorsGiven an array with n objects colored red, white or blue, sort them so that objects of th ...

  2. 【LeetCode】147. Insertion Sort List 解题报告(Python)

    [LeetCode]147. Insertion Sort List 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: h ...

  3. LeetCode: Combination Sum 解题报告

    Combination Sum Combination Sum Total Accepted: 25850 Total Submissions: 96391 My Submissions Questi ...

  4. 【LeetCode】Permutations 解题报告

    全排列问题.经常使用的排列生成算法有序数法.字典序法.换位法(Johnson(Johnson-Trotter).轮转法以及Shift cursor cursor* (Gao & Wang)法. ...

  5. LeetCode - Course Schedule 解题报告

    以前从来没有写过解题报告,只是看到大肥羊河delta写过不少.最近想把写博客的节奏给带起来,所以就挑一个比较容易的题目练练手. 原题链接 https://leetcode.com/problems/c ...

  6. C#版 - LeetCode 148. Sort List 解题报告(归并排序小结)

    leetcode 148. Sort List 提交网址: https://leetcode.com/problems/sort-list/  Total Accepted: 68702 Total ...

  7. 【LeetCode】75. Sort Colors 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 计数排序 双指针 日期 题目地址:https://l ...

  8. 【LeetCode】148. Sort List 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.c ...

  9. 【LeetCode】791. Custom Sort String 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 按顺序构造字符串 排序 日期 题目地址:https: ...

随机推荐

  1. ActiveMq C#客户端 消息队列的使用(存和取)

    1.准备工具 VS2013Apache.NMS.ActiveMQ-1.7.2-bin.zipapache-activemq-5.14.0-bin.zip 2.开始项目 VS2013新建一个C#控制台应 ...

  2. Android开发之动态检索(Filter)联系人

    1. 将所有联系人都转换为数字串,存到列表中. 将联系人姓名转换为数字串.例如,张丽思创->zlsc->9572. 过程解析: 张 – zhang – z – 9 丽 – li – l – ...

  3. HDUOJ--8球胜负

    8球胜负 Time Limit: 5000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Total Submi ...

  4. Windows右键菜单设置与应用技巧

    http://blog.163.com/lee_honleon/blog/static/555251522008014258896/   需要修改注册表,挺麻烦的.最好还是把迅雷卸了重装,不会影响什么 ...

  5. SolrCloud之分布式索引及与Zookeeper的集成--转载

    原文地址:http://josh-persistence.iteye.com/blog/2234411 一.概述 Lucene是一个Java语言编写的利用倒排原理实现的文本检索类库,Solr是以Luc ...

  6. Tomcat配置+JSP页面模板修改UTF-8

    A.修改Tomcat端口号步骤:1.找到Tomcat目录下的conf文件夹2.进入conf文件夹里面找到server.xml文件3.打开server.xml文件4.在server.xml文件里面找到下 ...

  7. Spring MVC POST中文乱码解决方案

    spring Web MVC框架提供了org.springframework.web.filter.CharacterEncodingFilter用于解决POST方式造成的中文乱码问题,具体配置如下: ...

  8. JFinal常见问题和知识点笔记

    1.当主键Id命名不是“id”时,应该显式地将自定义的id指出来 例如: Db.deleteById("post_user","user_id", 5); 2. ...

  9. php 文件上传,下载

    文件下载: html: <html> <body> <a href="1.rar">下载1.rar</a> <br /> ...

  10. POSIX 共享内存和 系列函数

    在前面介绍了system v 共享内存的相关知识,现在来稍微看看posix 共享内存 和系列函数. 共享内存简单来说就是一块真正的物理内存区域,可以使用一些函数将这块区域映射到进程的地址空间进行读写, ...