148Sort List
来源:互联网 发布:java类库观察者模式 编辑:程序博客网 时间:2024/06/06 07:09
模板题。这个题的要求是让我们找出一种时间复杂度是O(nlog(n)),空间复杂度是常数级的。这个就可以这么办,使用slow-fast技术将链表分成两部分,所谓slow-fast技术是指,快指针走两个,慢指针走一个,当快指针到头了,慢指针恰好指向中心。这样我们就不需要额外的空间了。代码如下:
class Solution {public: ListNode *sortList(ListNode *head) { if(!head||!head->next) return head; return mergeSort(head); } ListNode * mergeSort(ListNode *head){ if(!head||!head->next) //just one element return head; ListNode *p=head, *q=head, *pre=NULL; while(q&&q->next!=NULL){ q=q->next->next; pre=p; p=p->next; //divide into two parts } pre->next=NULL; ListNode *lhalf=mergeSort(head); ListNode *rhalf=mergeSort(p); //recursive return merge(lhalf, rhalf); //merge } ListNode * merge(ListNode *lh, ListNode *rh){ ListNode *temp=new ListNode(0); ListNode *p=temp; while(lh&&rh){ if(lh->val<=rh->val){ p->next=lh; lh=lh->next; } else{ p->next=rh; rh=rh->next; } p=p->next; } if(!lh) p->next=rh; else p->next=lh; p=temp->next; temp->next=NULL; delete temp; return p; } };
0 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
- LeeCode 148 Sort List
- 【leetcode 148 Sort List】
- 148Sort 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
- 最后一公里极速配送(三)
- 线段树区间和最大值
- 使用Jack编译
- OC中的NSDate
- BZOJ 3289 Mato的文件管理 莫队算法+树状数组
- 148Sort List
- mac下安装php的mssql.so扩展
- Visual Assist的Syntax Coloring功能失效的解决方法
- Java中String类的内存分配
- spring-cloud-netflix eureka服务添加基本用户验证
- 【疯狂Java】开发工具、eclipse配置、游戏引擎搭建
- 关于Python 多进程编程
- Xcode 7.3 自定义类无法自动联想的解决办法
- Android 计步器