文章目錄
題目描述
思路 & 代碼
- 轉化成:歸并排序 + 合并兩個有序鏈表 即可
- 利用快慢指針來拆分成兩條鏈表
- 注意:鏈表的拆分 & 連接
- 時間復雜度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
;}}
}
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎
總結
以上是生活随笔為你收集整理的【LeetCode笔记】148. 排序链表(Java、归并排序、快慢指针、双重递归)的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。