题目描述
在O(n log n)的时间内使用常数级空间复杂度对链表进行排序。
示例
输入
{30,20,40}
返回值
{20,30,40}
思路
题目要求复杂度为O(nlogn), 故可以考虑归并排序的思想。
归并排序算法描述:
- 步骤一:将待排序数组(链表)取中点并一分为二;
- 步骤二:递归地对左半部分和右半部分进行归并排序;
- 步骤三:将两个部分进行合并(merge),得到结果。
解答
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类
* @return ListNode类
*/
public ListNode sortList (ListNode head) {
if(head == null || head.next == null) return head;
// 快慢指针,slow到达中间,fast到达末尾
ListNode slow = head, fast = head.next;
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
}
ListNode right = sortList(slow.next);
slow.next = null;
ListNode left = sortList(head);
return merge(left, right);
}
ListNode merge(ListNode left, ListNode right){
if(left == null) return right;
if(right == null) return left;
ListNode dummy = new ListNode(0);
ListNode head = dummy;
while(left != null && right != null){
if(left.val > right.val){
head.next = right;
right = right.next;
}
else {
head.next = left;
left = left.next;
}
head = head.next;
}
if(left != null) head.next = left;
if(right != null) head.next = right;
return dummy.next;
}
}