LeetCode: Sort List 解题报告
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 解题报告的更多相关文章
- LeetCode: Sort Colors 解题报告
Sort ColorsGiven an array with n objects colored red, white or blue, sort them so that objects of th ...
- 【LeetCode】147. Insertion Sort List 解题报告(Python)
[LeetCode]147. Insertion Sort List 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: h ...
- LeetCode: Combination Sum 解题报告
Combination Sum Combination Sum Total Accepted: 25850 Total Submissions: 96391 My Submissions Questi ...
- 【LeetCode】Permutations 解题报告
全排列问题.经常使用的排列生成算法有序数法.字典序法.换位法(Johnson(Johnson-Trotter).轮转法以及Shift cursor cursor* (Gao & Wang)法. ...
- LeetCode - Course Schedule 解题报告
以前从来没有写过解题报告,只是看到大肥羊河delta写过不少.最近想把写博客的节奏给带起来,所以就挑一个比较容易的题目练练手. 原题链接 https://leetcode.com/problems/c ...
- C#版 - LeetCode 148. Sort List 解题报告(归并排序小结)
leetcode 148. Sort List 提交网址: https://leetcode.com/problems/sort-list/ Total Accepted: 68702 Total ...
- 【LeetCode】75. Sort Colors 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 计数排序 双指针 日期 题目地址:https://l ...
- 【LeetCode】148. Sort List 解题报告(Python & C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.c ...
- 【LeetCode】791. Custom Sort String 解题报告(Python & C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 按顺序构造字符串 排序 日期 题目地址:https: ...
随机推荐
- bash: fork: Resource temporarily unavailable
Last login: Wed Jul 26 09:19:11 2017 from ... -bash: fork: Resource temporarily unavailable -bash-3. ...
- spyder python 相关
1.python开发集成工具Spyder中,如何设置变量成员提示和代码补全呢? 答: pip install rope,安装好rope 就可以了 2.最常用的是:tap的制动补全 (IPython c ...
- SQL Server死锁排查经历 -基于SqlProfiler
提到sql server,想必最让人头疼的当属锁机制了.在默认的read committed隔离模式下,连最基本的select操作都要申请各种粒度的锁,而且在读取数据过程中会不断有锁升级.转化.在非 ...
- Eclipse集成ijkplayer并实现本地和网络视频播放等
概述 Eclipse 集成ijkplayer demo,播放本地视频.和rtmp流. 详细 代码下载:http://www.demodashi.com/demo/10630.html 原文地址:Ecl ...
- 实战:INNOBACKUPEX for mysql 5.6自己主动备份脚本
#backup.sh #!/bin/sh # # 第一次运行它的时候它会检查是否有全然备份,否则先创建一个全库备份 # 当你再次执行它的时候.它会依据脚本中的设定来基于之前的全库备份进行增量备份 #o ...
- C++知识整理(在此感谢大牛的整理)
这篇文章主要讲解如何在C++中使用cin/cout进行高级的格式化输出操作,包括数字的各种计数法(精度)输出,左或右对齐,大小写等等.通过本文,您可以完全脱离scanf/printf,仅使用cin/c ...
- supervisor+gunicorn部署python web项目
有了Nginx,对于Tomcat没有必要详细了解. 有了supervisor,再也没有必要把一个程序设置成服务.驻留进程,supervisor真是一个相见恨晚的好工具. 在Tomcat中,所有的web ...
- java IO 入门例子
import java.io.File; /** * File类型基本操作 */ /** * @author Administrator * */ public class FileDemo { /* ...
- 使用SecureCRT连接linux
1.登录之后进入linux系统,输入ifconfig(interfaces config)查看网卡信息 2.设置VMWare的虚拟机连接方式为仅主机模式 3.查看VMWare为仅主机模式虚拟网卡IP地 ...
- 基于HTTP在互联网传输敏感数据的消息摘要、签名与加密方案
基于HTTP在互联网传输敏感数据的消息摘要.签名与加密方案 博客分类: 信息安全 Java 签名加密AESMD5HTTPS 一.关键词 HTTP,HTTPS,AES,SHA-1,MD5,消息摘要,数 ...