Leetcode: Sort List
来源:互联网 发布:学软件开发工资待遇 编辑:程序博客网 时间:2024/05/18 04:01
Sort List
Sort a linked list in O(n log n) time using constant space complexity.
解析:
由于要求时间复杂度为O(n log n),空间复杂度为O(n),使用分治类的排序算法才能符合要求。这里采取的是归并排序,运用递归将原始链表进行分割,然后再把子链表依次按顺序合并,实现排序目的。
代码:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution { public ListNode sortList(ListNode head) { return Split(head); } private ListNode Split(ListNode head1) { if(head1==null||head1.next==null)return head1; ListNode fast = head1; ListNode slow = head1; while(fast.next!=null && fast.next.next!=null) {slow=slow.next;fast=fast.next.next;} ListNode head2 = slow.next; slow.next = null; return Merge(Split(head1),Split(head2)); } private ListNode Merge(ListNode n1, ListNode n2) { ListNode dummy = new ListNode(0); ListNode pre = dummy; while(n1!=null && n2!=null) { if(n1.val<n2.val) {pre.next=n1;n1=n1.next;} else {pre.next=n2;n2=n2.next;} pre = pre.next; } if(n1==null)pre.next = n2; if(n2==null)pre.next = n1; return dummy.next; }}
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
- 推荐算法:基于特征的推荐算法
- oracle包
- Shell中的循环语句for、while、until实例讲解
- leetCode:Count Complete Tree Nodes
- 混合自回归移动平均过程
- Leetcode: Sort List
- 学习笔记(objective-c)-继承
- eclipse+CDT调试segmentation fault错误
- node.js发送邮件
- RSA 公钥密码实验1
- 1. 推荐引擎初探
- 磁盘文件系统Fat、Fat32、NTFS、exFAT的优缺点
- Sprite Kit Swift游戏开发新手指导手册(2)
- iOS 之 Thread Runloop浅显认识说起