題意描述:
在 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]
總結:
- 標準答案是 歸併排序,尚未實現,待定。