【Leet Code】148. Sort List---Medium
2015-09-15 16:13
399 查看
Sort a linkedlist in O(n log n) time using
constant space complexity.
思路:
借助2-路归并排序实现。
基本思想:
归并排序(Merging Sort)法是将两个(或两个以上)有序表合并成一个新的有序表,即把待排序序列分为若干个子序列,每个子序列是有序的。然后再把有序子序列合并为整体有序序列。
时间复杂度:O(nlog(n)),空间复杂度:O(n)。稳定排序算法。
归并排序示例:
2-路归并排序:
核心操作:将一维数组中前后相邻的两个有序序列归并为一个有序序列。
Note:在实现该算法中,对于排序使用了递归。对于非linkList,可以实现非递归,可以参考博客:http://blog.csdn.net/lili616/article/details/47701447
constant space complexity.
思路:
借助2-路归并排序实现。
基本思想:
归并排序(Merging Sort)法是将两个(或两个以上)有序表合并成一个新的有序表,即把待排序序列分为若干个子序列,每个子序列是有序的。然后再把有序子序列合并为整体有序序列。
时间复杂度:O(nlog(n)),空间复杂度:O(n)。稳定排序算法。
归并排序示例:
2-路归并排序:
核心操作:将一维数组中前后相邻的两个有序序列归并为一个有序序列。
Note:在实现该算法中,对于排序使用了递归。对于非linkList,可以实现非递归,可以参考博客:http://blog.csdn.net/lili616/article/details/47701447
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* mergeList(ListNode* beg1, ListNode* beg2) { if (!beg1 && !beg2 || beg1 && !beg2) return beg1; if (!beg1 && beg2 ) return beg2; ListNode* p1 = beg1; ListNode* p2 = beg2; ListNode* result = beg1; if (p1->val > p2->val) { result = p2; p2 = p2->next; } else p1 = p1->next; ListNode* curInsert = result; while (p1 && p2) { while (p1 && p1->val <= p2->val) { curInsert->next = p1; curInsert = p1; p1 = p1->next; } while (p1 && p2 && p2->val <= p1->val) { curInsert->next = p2; curInsert = p2; p2 = p2->next; } } while (p1) { curInsert->next = p1; curInsert = p1; p1 = p1->next; } while (p2) { curInsert->next = p2; curInsert = p2; p2 = p2->next; } curInsert->next = NULL; return result; } ListNode* sortListRecur(ListNode* head) { if (!head || !head->next) return head; ListNode* q = head; ListNode* p = head->next; // split the list to two lists while (p && p->next) { q = q->next; if (p->next) p = p->next->next; } ListNode* head2 = q->next; q->next = NULL; // sort the two list first ListNode* result1 = sortListRecur(head); ListNode* result2 = sortListRecur(head2); // merge list head1 with list head2 result1 = mergeList(result1, result2); return result1; } ListNode* sortList(ListNode* head) { if (!head) return head; head = sortListRecur(head); return head; } };
相关文章推荐
- C#获取管理员权限
- CoreGraphics QuartzCore CGContextTranslateCTM 用法
- HUD 5256 序列变换
- XMLHttpRequest cannot load"url"Cross origin requests are only supported. send @ jquery-2.1.4.js:8630
- linux命令之top
- cocos studio2.x 对象绑定
- 数据库连接字符串简析
- Quartz实现定时任务的配置方法
- ASP.NET MVC 缓存使用示例
- hibernate核心开发接口
- android+ADT+SDK开发环境及变量配置
- hdu5446(2015长春网络赛J题)
- MongoDB常用操作
- 简单工厂
- 黑马程序员学习(五)Final、接口、多态
- NHibernate从入门到精通系列(2)——NHibernate环境与结构体系
- PLC实现重复定时
- 蚁群算法、遗传算法、模拟退火算法介绍
- Friendship (poj 1815 最小点割集+枚举)
- exec家族