LeetCode 解题报告 Sort List
2014-11-02 16:30
465 查看
Sort a linked list in O(n log n)
time using constant space complexity.
分析:对链表进行排序,如果是单链表用归并排序时最快的,并且在对数组进行归并的时候是需要用到O(n)的空间的,但是链表就不需要了,只要有O(1)的空间就够了,因为不需要辅助变量来存储。
首先是递归的将链表拆分开,然后将链表进行合并。
下面是代码:
time using constant space complexity.
分析:对链表进行排序,如果是单链表用归并排序时最快的,并且在对数组进行归并的时候是需要用到O(n)的空间的,但是链表就不需要了,只要有O(1)的空间就够了,因为不需要辅助变量来存储。
首先是递归的将链表拆分开,然后将链表进行合并。
下面是代码:
<span style="font-family:Helvetica Neue, Helvetica, Arial, sans-serif;color:#333333;">public ListNode sortList(ListNode head){ if(head == null || head.next == null) return head; //find the middle node ListNode fast = head,slow = head; while(fast.next != null && fast.next.next != null){ fast = fast.next.next; slow = slow.next; } //diconnect the List fast = slow; slow = slow.next; fast.next = null; //Recursive ListNode l1 = sortList(head); ListNode l2 = sortList(slow); //Meger the List return MegerList(l1,l2); } public ListNode MegerList(ListNode l1,ListNode l2){ ListNode head = new ListNode(-1); for(ListNode p = head;l1 != null || l2 != null; p = p.next){ int val1 = l1 == null?Integer.MAX_VALUE:l1.val; int val2 = l2 == null?Integer.MAX_VALUE:l2.val; if(val1 <= val2){ p.next = l1; l1 = l1.next; }else{ p.next = l2; l2 = l2.next; } } return head.next; }</span>
相关文章推荐
- [leetcode] 147. Insertion Sort List 解题报告
- leetcode 148. Sort List 解题报告
- [leetcode] 148. Sort List 解题报告
- Leetcode Insertion Sort List 解题报告
- Leetcode Sort List 解题报告
- leetCode解题报告之Sort List
- LeetCode—Sort List解题报告
- [LeetCode]Sort List,解题报告
- [Leetcode] 147. Insertion Sort List 解题报告
- Leetcode Insertion Sort List 解题报告
- LeetCode: Insertion Sort List 解题报告
- LeetCode—Insertion Sort List 解题报告
- [Leetcode] 148. Sort List 解题报告
- LeetCode 148. Sort List 解题报告(归并排序小结)
- leetCode解题报告之Insertion Sort List
- LeetCode解题报告—— Rotate List & Set Matrix Zeroes & Sort Colors
- LeetCode Sort List 解题报告
- 【LeetCode】Sort List 解题报告(对链表进行归并排序)
- 【LeetCode】Insertion Sort List 解题报告
- 景岁的Leetcode解题报告:147.Insertion Sort List (Java)