148. 排序链表
问题描述
在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。
示例 1:
输入: 4->2->1->3
输出: 1->2->3->4
示例 2:
输入: -1->5->3->4->0
输出: -1->0->3->4->5
思路
使用自顶向下的归并排序
实现
/**
* 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 fast = head;
ListNode slow = head;
while(fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
ListNode next = slow.next;
slow.next = null;
return merger(sortList(head), sortList(next));
}
private ListNode merger(ListNode left, ListNode right) {
ListNode temp = new ListNode(0);
ListNode cur = temp;
while(left != null && right != null) {
if(left.val > right.val) {
cur.next = right;
right = right.next;
} else {
cur.next = left;
left = left.next;
}
cur = cur.next;
}
if(left != null) {
cur.next = left;
}
if(right != null) {
cur.next = right;
}
return temp.next;
}
}
链表归并排序
本文介绍了一种在O(nlogn)时间复杂度和常数级空间复杂度下,对链表进行排序的方法。通过自顶向下的归并排序策略,实现链表的有效排序。示例包括将无序链表4->2->1->3排序为1->2->3->4,以及将-1->5->3->4->0排序为-1->0->3->4->5。
585

被折叠的 条评论
为什么被折叠?



