[LeetCode] Sort List
来源:互联网 发布:麻瓜网络 编辑:程序博客网 时间:2024/06/10 05:02
问题:
Sort a linked list in O(n log n) time using constant space complexity.
分析:
用divide and conquer。首先遍历一次,找到长度;然后遍历一半,找到中间点;然后在左右两半recursion,然后merge。
Time complexity: T(n) = 2T(n/2) + n = O(n log n)。
代码:
ListNode *mergeList(ListNode *left, ListNode *right) {ListNode dummy(0);ListNode *curr = &dummy;while (left || right) {if (!left) {curr->next = right;break;}if (!right) {curr->next = left;break;}int l = left->val;int r = right->val;if (l < r) {curr->next = left;left = left->next;curr = curr->next;}else {curr->next = right;right = right->next;curr = curr->next;}}return dummy.next;}class Solution {public: ListNode *sortList(ListNode *head) {if (!head)return head;int n = 0;ListNode *curr = head;while (curr) {n ++;curr = curr->next;}if (n == 1)return head;int half = n / 2;curr = head;for (int i = 0; i < half; i ++) {curr = curr->next;}ListNode * right = curr->next;curr->next = NULL;ListNode * left = sortList(head);right = sortList(right);return mergeList(left, right);}};
0 0
- [leetcode][list][sort] Sort List
- Insertion Sort List | leetcode
- Leetcode: Insertion Sort List
- [LeetCode] Insertion Sort List
- Leetcode: Insertion Sort List
- Leetcode: Sort List
- Sort List | leetcode
- leetcode-Sort List
- leetcode-Insertion Sort List
- LeetCode题解:Sort List
- leetcode 134: Sort List
- [LeetCode]Sort List
- [LeetCode]Insertion Sort List
- [LeetCode] Sort List
- 【LeetCode】Insertion Sort List
- leetCode - Sort List
- LeetCode | Insertion Sort List
- LeetCode - Insertion Sort List
- Ext4.x 之了解基本体系结构
- 【error】cookie报错中文报错
- jsp中文显示乱码解决方案
- 知识点总结2 External Sorting, Bucket Sorting, and Radix Sorting
- 室内定位技术
- [LeetCode] Sort List
- Generate Parentheses 比较不错的思路解法
- js事件处理方法addEventListener和attachEvent
- 几种室内无线定位技术简介
- 在visual studio 2010之中调试带参数的程序
- 如何:使用调试器变量窗口
- XML 的 DOM 解析范例:将XML用作数据库
- 夏虫语冰——写在前面
- Ubuntu SDK 第一节 -- 创建一个简单的QML应用