题意描述:
在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。
示例:
示例一:
输入: 4->2->1->3
输出: 1->2->3->4
示例二:
输入: -1->5->3->4->0
输出: -1->0->3->4->5
解题思路:
Alice: 快速排序你会写吗 ?
Bob: 以前会写,现在好像不太会了。这道题目需要用快速排序吗,链表是单向链表呀,能够使用快速排序来写吗 ?
Alice: 不知道,我也不会快速排序。那就 ┓( ´∀` )┏ 看来又到了学习的时候了。
Bob: 我们可以把链表中的值取出来,然后排序,然后再送到链表中去。
Alice: emmm, 这样时间复杂度 能够达到 O(n log n),空间复杂度是O (n)。
Bob: 用冒泡排序也可以试一试,冒泡排序应该是单向连接的链表就可以了。
Alice: 但是冒泡排序是 O(n^2) 的时间复杂度呀,会超时啊。
Bob: 所以说试试嘛 😎。
Alice: 听说标准答案是 分治法 ?
Bob: 分治法我也不会呀 😵
Alice: 那就等你有时间再来补题吧。
Bob: ヽ( ̄▽ ̄)و好的。
代码:
Python 方法一: O(nlogn) 排序 + O(n)内存。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def sortList(self, head: ListNode) -> ListNode:
tmp = []
node = head
while node != None:
tmp.append(node.val)
node = node.next
tmp.sort()
node = head
cnt = 0
while node != None:
node.val = tmp[cnt]
cnt += 1
node = node.next
return head
Java 方法一:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode sortList(ListNode head) {
if(head == null){
return null;
}
ArrayList<Integer> tmp = new ArrayList<Integer>();
ListNode node = head;
while(node != null){
tmp.add(node.val);
node = node.next;
}
int[] data = new int[tmp.size()];
for(int i=0; i<tmp.size(); ++i){
data[i] = tmp.get(i);
}
Arrays.sort(data);
node = head;
int cnt = 0;
while(node != null){
node.val = data[cnt];
cnt ++;
node = node.next;
}
return head;
}
}
Python 方法二:冒泡排序,超时
。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def sortList(self, head: ListNode) -> ListNode:
if head == None:
return None
node = head
while node.next != None:
nextNode = node.next
while nextNode != None:
if node.val > nextNode.val:
node.val, nextNode.val = nextNode.val, node.val
nextNode = nextNode.next
node = node.next
return head
Java 方法二: 冒泡排序,O(n*2)时间复杂度,常数级别空间复杂度。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode sortList(ListNode head) {
if(head == null){
return null;
}
int tmp = 0;
ListNode node = new ListNode(0);
ListNode nextNode = new ListNode(0);
for(node=head; node.next!=null; node=node.next){
for(nextNode=node.next; nextNode!=null; nextNode=nextNode.next){
if(node.val > nextNode.val){
tmp = node.val;
node.val = nextNode.val;
nextNode.val = tmp;
}
}
}
return head;
}
}
易错点:
- 一些测试用例:
[4,2,1,3]
[-1,5,3,4,0]
[]
[2,1]
[1]
- 答案:
[1,2,3,4]
[-1,0,3,4,5]
[]
[1,2]
[1]
总结:
- 标准答案是 归并排序,尚未实现,待定。