LeetCode:Sort List
来源:互联网 发布:mac如何安装windows10 编辑:程序博客网 时间:2024/06/05 09:40
Sort List
Total Accepted: 68684 Total Submissions: 278057 Difficulty: Medium
Sort a linked list in O(n log n) time using constant space complexity.
Subscribe to see which companies asked this question
Hide Similar Problems
思路:
1.nlogn的排序算法有:快排、归并、堆排;
2.但是快排对链表不适合;
3.数组中归并的空间复杂度为O(n),但是链表可以直接归并只需要O(1)的空间复杂度。
code:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode *merge(ListNode *h1, ListNode *h2){ if(!h1) return h2; if(!h2) return h1; ListNode p(0); ListNode *t = &p; while(h1 && h2){ if(h1->val < h2->val){ t->next = h1; h1 = h1->next; }else{ t->next = h2; h2 = h2->next; } t = t->next; } t->next = h1 ? h1:h2; return p.next; } ListNode* sortList(ListNode* head) { // 空或只有一个结点,直接返回 if(!head || !head->next) return head; // 利用快、慢指针找到中间结点 ListNode *slow = head,*fast = head; while(fast && fast->next && fast->next->next){ slow = slow->next; fast = fast->next->next; } ListNode *h2 = sortList(slow->next); // 后半部分 slow -> next = NULL; // 这里要先断链才能进行前半部分的归并 ListNode *h1 = sortList(head); // 前半部分 return merge(h1,h2); }};
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
- 【Adb connection Error:远程主机强迫关闭了一个现有的连接】错误解决方法
- C++多态篇2——虚函数表详解之从内存布局看函数重载,函数覆盖,函数隐藏
- 收到来自其他应用程序的简单的数据
- fzu2215 中缀表达式展开求多项式系数(模拟)【中缀转后缀模板】
- 安装cocoapods步骤,及遇到问题解决
- LeetCode:Sort List
- 中国剩余定理的学习
- android中通过自定义xml实现你需要的shape效果 xml属性配置
- Apache 的安装与实践
- 程序员学习视频汇总
- 数据结构笔记整理第2章:线性表
- Datagridview控件实现下拉列表(DataGridViewComboBoxColumn)
- firefox 编程 使用插件
- Linux-Root权限删除文件删除不了