【Leetcode】Sort List
来源:互联网 发布:哪里能买到大数据 编辑:程序博客网 时间:2024/04/25 20:21
【题目】
Sort a linked list in O(n log n) time using constant space complexity.
【代码】
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:ListNode *mergeSort(ListNode *head,ListNode *secondHead){ ListNode *index1=head,*index2=secondHead,*pre=new ListNode(0); ListNode *result=pre; while(index1&&index2){ if(index1->val<index2->val){ pre->next=index1; index1=index1->next; } else{ pre->next=index2; index2=index2->next; } pre=pre->next; } if(index1)pre->next=index1; if(index2)pre->next=index2; return result->next;} ListNode *sortList(ListNode *head) { int len=0; ListNode *p=head; while(p){ ++len; p=p->next; } if(len<=1)return head; ListNode *mid=head; int num=len/2-1; while(num--)mid=mid->next; ListNode *secondHead=mid->next; mid->next=NULL; return mergeSort(sortList(head),sortList(secondHead)); }};
【总结】
1.能在O(nlogn)时间内排序的方法有:快速排序、归并排序和堆排序,快速排序适合于能随机访问的数据结构。
2.归并排序的基本思想:三步骤:分解、排序、归并。找出要排序序列的中点,将序列分解为两部分,分别对其排序,然后归并为一个序列。这是个递归的过程。
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
- 数据挖掘:数据挖掘Apriori算法
- jquery控制select的值,选中状态
- 重写类的equals方法
- oj C++继承(改错题)
- java中 Random类的用法
- 【Leetcode】Sort List
- 鱼类小志
- SourceTree 添加远程仓库时报错
- 无锁队列的环形数组实现(Lock Free Queue Implementation in Ring Array)
- #include #import @class
- 我的算法学习之路
- dos中ren命令与通配符的使用
- C语言之指针、数组和函数
- 走!翻越这座山,遇见更好的自己