【LeetCode】 sort list 单链表的归并排序
来源:互联网 发布:新东方网络课程百度云 编辑:程序博客网 时间:2024/05/16 13:58
题目:Sort a linked list in O(n log n) time using constant space complexity.
思路:要求时间复杂度O(nlogn)
知识点:归并排序,链表找到中点的方法
存在的缺点:边界条件多考虑!!!
/** * LeetCode Sort List Sort a linked list in O(n log n) time using constant space complexity. * 题目:将一个单链表进行排序,时间复杂度要求为o(nlogn) * 思路:1时间复杂度为o(nlog n)的排序算法有:归并排序、快排(期望)、堆排序 * 2、单链表排序用归并排序,双链表排序用快排 * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ package javaTrain;class ListNode { int val; ListNode next; ListNode(int x) { val = x; next = null; }}public class Train4 { public ListNode sortList(ListNode head) {if(head == null || head.next == null)return head;ListNode fast = head;ListNode slow = head;while(fast.next.next != null && slow.next != null){fast = fast.next.next;//使得当遍历完该链表之后一个指向中间一个指向末尾,即找到链表中点slow = slow.next;}ListNode list2 = slow.next;slow.next = null;head = sortList(head);list2 = sortList(list2);return merge(head,list2);}private static ListNode merge(ListNode list1,ListNode list2){if(list1 == null) return list2;if(list2 == null) return list1;ListNode head = new ListNode(0);ListNode last = head; while(list1.next != null && list2.next != null){if(list1.val <= list2.val){last.next = list1;list1 = list1.next;}else{last.next = list2;list2 = list2.next;}last = last.next;}if(list1 != null)last.next = list1;else if(list2 != null)last.next = list2;return head.next;}}
1 0
- 【LeetCode】 sort list 单链表的归并排序
- Leetcode:Sort List 对单链表归并排序
- 【leetcode 单链表归并排序】Sort List
- LeetCode Sort List(单链表归并排序)
- sort list leetcode (归并排序)
- leetcode:Sort List(链表的归并排序)
- LeetCode Sort List 链表的归并排序
- leetcode:Sort List 使用归并排序的解决思路
- Leetcode Sort List 链表归并排序
- [leetcode] 134 Sort List (链表 & 归并排序)
- Leetcode: Sort List - 归并
- 归并排序---Sort List
- [C++]LeetCode: 125 Sort List (归并排序链表)
- LeetCode 148. Sort List 解题报告(归并排序小结)
- leetcode 148. Sort List 链表归并排序
- Sort List[leetcode] 由归并排序的递归和循环,到本题的两种解法
- Sort List——链表的快速/归并排序
- 链表的二路归并排序 Sort List
- hdu 1066
- Xcode6.1 模拟器路径
- 像狗一样奔跑
- Object - C运行时应用(三)——实现NSCoding的自动归档和自动解档
- [Leetcode] 43. Multiply Strings
- 【LeetCode】 sort list 单链表的归并排序
- Android实现可拖拽的ListView
- Chrome development tools学习笔记(3)
- 大写转换成小写
- day09-cookie&sessionの代码学习
- 十一、Linux系统编程-进程(四)替换进程映像exe函数族
- Perl 监控日志异常报警
- 10->命令orapwd的学习
- [Leetcode] 44. Wildcard Matching