题目描述
难点在于时空复杂度的要求
思路 & 代码
转化成:归并排序 + 合并两个有序链表 即可 利用快慢指针来拆分成两条链表 注意:链表的拆分 & 连接 时间复杂度O(n * logn),空间复杂度 O(1)
class Solution { public ListNode sortList ( ListNode head) { if ( head == null || head. next == null ) { return head; } ListNode fast = head; ListNode slow = head; while ( fast != null && fast. next != null ) { slow = slow. next; fast = fast. next. next; } if ( slow. next == null ) { slow = head; } fast = sortList ( slow. next) ; slow. next = null ; slow = sortList ( head) ; return mergeSortedList ( slow, fast) ; } ListNode mergeSortedList ( ListNode head1, ListNode head2) { if ( head1 == null ) { return head2; } if ( head2 == null ) { return head1; } if ( head1. val < head2. val) { head1. next = mergeSortedList ( head1. next, head2) ; return head1; } else { head2. next = mergeSortedList ( head1, head2. next) ; return head2; } }
}
二刷
好吧…记得思路是快慢指针 + 合并有序链表,但是具体咋写确实回想不起来= = 其实就是两个函数:快慢指针二分链表 + 合并两个有序链表 ,双重递归!
class Solution { public ListNode sortList ( ListNode head) { if ( head == null || head. next == null ) { return head; } ListNode slow = head, fast = head; while ( fast != null && fast. next != null ) { slow = slow. next; fast = fast. next. next; } if ( slow. next == null ) { slow = head; } fast = sortList ( slow. next) ; slow. next = null ; slow = sortList ( head) ; return mergeSort ( slow, fast) ; } public ListNode mergeSort ( ListNode headA, ListNode headB) { if ( headB == null ) { return headA; } if ( headA == null ) { return headB; } if ( headA. val < headB. val) { headA. next = mergeSort ( headA. next, headB) ; return headA; } else { headB. next = mergeSort ( headA, headB. next) ; return headB; } }
}