排序算法:
时间复杂度为 O(nlgn):
quick sort (空间复杂度O(1)), merge sort(空间复杂度O(n)), heap sort (空间复杂度O(1))
时间复杂度为 O(n):
bucket sort, radix sort,
基于比较的排序,时间复杂度一般为O(nlgn)
Question
Sort a linked list in O(n log n) time using constant space complexity.
Explanation
这道题主要要掌握几种sort的方法怎么写,还有相关的复杂度分析。
Code
-
Merge Sort: 时间复杂度为O(nlogn),空间复杂度O(n)
12345678910111213141516171819202122232425262728293031323334353637383940414243444546public class Solution {public ListNode sortList(ListNode head) {if (head == null || head.next == null) return head;// Merge SortListNode mid = findMiddle(head);ListNode right = sortList(mid.next);mid.next = null;ListNode left = sortList(head);return mergeTwoLists(left, right);}public ListNode mergeTwoLists(ListNode l1, ListNode l2) {ListNode a = l1;ListNode b = l2;if (l1 == null && l2 == null) return null;ListNode curr = new ListNode(0);ListNode dummy= curr;while(a != null && b != null) {if (a.val < b.val) {dummy.next = new ListNode(a.val);a = a.next;} else {dummy.next = new ListNode(b.val);b = b.next;}dummy = dummy.next;}if(a!= null) dummy.next = a;else dummy.next = b;return curr.next;}private ListNode findMiddle(ListNode head) {ListNode walker = head;ListNode runner = head.next;while(runner!= null && runner.next!=null) {runner = runner.next.next;walker = walker.next;}return walker;}} -
Quick Sort