LeetCode 148 Sort List
来源:互联网 发布:淘宝卖家体检中心在哪 编辑:程序博客网 时间:2024/05/01 23:24
题目描述
Sort a linked list in O(n log n) time using constant space complexity.
分析
O(n log n) 的时间复杂度,归并排序最好,因为它不会因为输入序列的基本有序而变化。
参考:LeetCode 021 Merge Two Sorted Lists
- 首先将List分成两个
- MergeSort(left) ,MegerSort(right)
- LeetCode 021 Merge Two Sorted Lists
代码
public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode rt = new ListNode(0); ListNode h = rt; while (l1 != null && l2 != null) { if (l1.val < l2.val) { rt.next = l1; l1 = l1.next; } else { rt.next = l2; l2 = l2.next; } rt = rt.next; } if (l1 != null) rt.next = l1; else rt.next = l2; return h.next; } public ListNode sortList(ListNode head) { if (head == null) return null; if (head.next == null) return head; ListNode fast = head.next; ListNode slow = head; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; } ListNode h2 = slow.next; slow.next = null; return mergeTwoLists(sortList(head), sortList(h2)); }
1 0
- LeetCode(148)Sort List
- LeetCode: Sort List [148]
- LeetCode 148 Sort List
- [leetcode 148] Sort List
- [LeetCode 148]Sort List
- leetcode-148 Sort List
- Leetcode 148 Sort List
- LeetCode 148: Sort List
- 【leetcode 148 Sort List】
- Leetcode[148]-Sort List
- Sort List - LeetCode 148
- Leetcode# 148 Sort List
- Leetcode # 148 Sort List
- LeetCode(148) Sort List
- leetcode 148: Sort List
- [Leetcode]#148 Sort List
- 148 Sort List [Leetcode]
- LeetCode 148 Sort List
- To Thine Own Self Be True
- 继承
- (转)iBaits中SqlMapClientTemplate的使用
- Meetings Don’t Write Code
- 盘点:10款适合创业团队使用的团队协作工具
- LeetCode 148 Sort List
- Chart a Course for Change
- xss攻击与解决方法!
- ORACLE去掉字符串前面的数值
- Ajax 超完整教程
- TCPIP三次握手与四次挥手
- HDU 5586 Sum
- 安装配置CAS server
- shell 将当前目录下所有文件的文件名逆序