題目描述:
在 O(n log n) 時間復雜度和常數(shù)級空間復雜度下,對鏈表進行排序胆筒。
示例 1:
輸入: 4->2->1->3
輸出: 1->2->3->4
示例 2:
輸入: -1->5->3->4->0
輸出: -1->0->3->4->5
思路:
題目要求在 O(n log n) 時間復雜度下解題畏鼓,在滿足這個時間復雜度的常見算法有快速排序酱酬,歸并排序,和堆排序云矫。歸并排序的重點是找到中間節(jié)點膳沽。
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) {
ListNode indexNode = head;
ListNode startNode = head;
if(head == null) return head;
while(indexNode.next != null)
{
boolean exchangeflag = true;
head = startNode;
while(head.next != null){
if(head.val > head.next.val)
{
int temp = head.val;
head.val = head.next.val;
head.next.val = temp;
exchangeflag = false;
}
head = head.next;
}
if(exchangeflag)
{
break;
}else{
indexNode = indexNode.next;
}
}
return startNode;
}
}
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 || head.next ==null) return head;
ListNode slow = head, fast = head.next;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
ListNode temp = slow.next;
slow.next = null;
ListNode left = sortList(head);
ListNode right = sortList(temp);
ListNode h = new ListNode(0);
ListNode ans = h;
while(left != null && right != null)
{
if(left.val < right.val)
{
h.next = left;
left = left.next;
}else{
h.next = right;
right = right.next;
}
h = h.next;
}
h.next = left != null ? left : right;
return ans.next;
}
}
[圖解] 歸并排序
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/sort-list