您的位置:首页 > 其它

148. Sort List

2015-05-09 11:31 169 查看
题目:

Sort a linked list in O(n log n) time using constant space complexity.

链接: http://leetcode.com/problems/sort-list/

题解:

Sort List, 链表排序,一看到O(nlogn)就想到使用merge sort。 对于merge sort,还要研究一下bottom-up和top-down的区别,优劣点,如何继续优化等等,比如n较小时使用insertion sort, 了解Python的Tim-sort之类。也要研究一下链表的Quicksort,以及3-way Quicksort。 当时电面Amazon的时候写排序作死选择Quicksort,还尝试写了一个3-way Quicksort,由于理解不深同时当天也头昏脑胀没解释清楚,被面试官白大姐秒拒,如此浪费一年机会,甚是可惜。对于各种排序的stalability也要好好复习。熟能生巧,多练吧。另外,external sorting,B tree,A* tree,indexing,paging之类的也要复习。聊远了...

这题使用Merge Sort的话,还是按照Divide-and-Conquer分治。 两个辅助方法是findMid找中点,以及merge合并。 merge的话完全可以使用"Merge Sorted List"的代码,找中点我们也使用过,所以可以直接写。

Time Complexity - O(nlogn), Space Complexity - O(logn)。

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode sortList(ListNode head) {
if(head == null || head.next == null)
return head;
ListNode mid = findMid(head);
ListNode right = sortList(mid.next);
mid.next = null;
ListNode left = sortList(head);

return merge(left, right);
}

private ListNode findMid(ListNode head) {        
if(head == null || head.next == null)
return head;
ListNode fast = head, slow = head;

while(fast.next != null && fast.next.next != null) {
fast = fast.next.next;
slow = slow.next;
}

return slow;
}

private ListNode merge(ListNode left, ListNode right) {
ListNode dummy = new ListNode(-1);
ListNode node = dummy;

while(left != null && right != null) {
if(left.val < right.val) {
node.next = left;
left = left.next;
} else {
node.next = right;
right = right.next;
}
node = node.next;
}

if(left != null)
node.next = left;
else
node.next = right;

return dummy.next;
}
}


到这里其实还没结束。仔细看题目要求constant space complexity。这样的话我们就不能使用递归了。下面是代码。 <- (二刷见)

Time Complexity - O(nlogn),Space Complexity - O(1)。

(未完待续)

Reference:
http://www.mathcs.emory.edu/~cheung/Courses/171/Syllabus/7-Sort/merge-sort5.html https://en.wikipedia.org/wiki/Merge_sort#Bottom-up_implementation https://leetcode.com/discuss/10264/my-o-n-log-n-time-o-1-space-solution https://leetcode.com/discuss/12014/my-iterative-merge-sort https://leetcode.com/discuss/15420/java-solution-with-strict-o-1-auxiliary-space-complexity https://leetcode.com/discuss/18210/i-think-my-java-solution-is-o-1-space https://leetcode.com/discuss/19119/java-merge-sort-solution-with-o-1-memory https://leetcode.com/discuss/24917/my-java-code-with-constant-space https://leetcode.com/discuss/28594/bottom-recurring-with-space-complextity-time-complextity https://leetcode.com/discuss/39867/java-solution-bottom-iterative-merge-with-detailed-comments
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: