[leetcode]Sort List
来源:互联网 发布:windows防火墙开关 编辑:程序博客网 时间:2024/06/15 22:04
Sort List
Sort a linked list in O(n log n) time using constant space complexity.
此方法利用快速排序思想,但因测试数据种类小数量大,而超时
class Solution {public: //快速排序,算法导论版, 从前向后进行的 ListNode* partition(ListNode *head, ListNode *tail){ ListNode *rear = head->next; ListNode *front = head; int x = head->val; for(ListNode *ptr = rear; ptr != tail; ptr = ptr->next){ if(ptr->val <= x){ swap(ptr->val, front->next->val); front = front->next; } } swap(head->val, front->val); return front; } void quicksort(ListNode *head, ListNode *tail){ if(head != tail){ ListNode *mid = partition(head, tail); quicksort(head, mid); quicksort(mid->next, tail); } } ListNode *sortList(ListNode *head) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. quicksort(head, NULL); return head; }};
利用了stl源码库中的map(以红黑树做为实现结构)
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode *sortList(ListNode *head) { if(NULL == head) return NULL; map<int, int> mii; ListNode *ptr = head; while(ptr){ mii[ptr->val]++; ptr = ptr->next; } ptr = head; while(ptr){ for(map<int, int>::iterator itor = mii.begin(); itor != mii.end(); itor++){ for(int i = 0; i < itor->second; i++){ ptr->val = itor->first; ptr = ptr->next; } } } return head; }};
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
- HTML <em> 标签
- linux杂谈(十七):iscsi存储分离技术
- 虚拟地址和物理地址的概念
- JavaSE 套接字Socket编程
- iOS bit to nsdata
- [leetcode]Sort List
- 物理地址和虚拟地址
- 广东:正式出台云计算发展规划,并提出三步走目标
- SG函数模板
- 简历编写四原则
- Win7 修改Winlogon.exe进程代码
- 关于 Java 中 finally 语句块的深度辨析
- 2014 华为编程 第二阶段
- adblock如何过滤百万级别规则