leetcode之时间复杂度为O(nlogn)的链表排序
来源:互联网 发布:数据分析的网站有哪些 编辑:程序博客网 时间:2024/05/20 16:35
3. Sort List
Sort a linked list in O(n log n) time using constant space complexity.
使用归并排序的思想,代码如下:
/** * Sort a linked list in O(n log n) time using constant space complexity. */package com.leetcode.program;import java.util.Random;public class SortLinkedList {public ListNode sortList(ListNode head){if(head == null || head.next == null)return head;ListNode midNode = findMiddleNode(head);if(midNode == null)return null;ListNode mid = midNode.next;midNode.next = null;ListNode h1 = sortList(head);ListNode h2 = sortList(mid);return mergeListNode(h1, h2);//return null;}private ListNode mergeListNode(ListNode h1, ListNode h2){ListNode hret = (h1 == null) ? h2 : h1;if(hret == null)return hret;hret = (h1.val < h2.val) ? h1 : h2;if(hret == h1)h1 = h1.next;elseh2 = h2.next;ListNode lashRet = hret;//the lash node of the returned Listwhile(h1 != null && h2 != null){if(h1.val < h2.val){lashRet.next = h1;lashRet = h1;h1 = h1.next;}else{lashRet.next = h2;lashRet = h2;h2 = h2.next;}}if(h1 != null)lashRet.next = h1;if(h2 != null)lashRet.next = h2;return hret;}/*寻找链表的中间节点*/private ListNode findMiddleNode(ListNode h){if(null == h || h.next == null)return h;ListNode midNode = h;while(h != null && h.next != null && h.next.next != null){h = h.next.next;midNode = midNode.next;}return midNode;}public static void main(String[] args) {Random rand = new Random();ListNode head = null;ListNode currentNode = null;for(int i = 0 ; i < 10; i ++){if(head == null){head = new ListNode(rand.nextInt(47));currentNode = head;}else{currentNode.next = new ListNode(rand.nextInt(47));currentNode = currentNode.next;}}SortLinkedList s = new SortLinkedList();ListNode mid = s.findMiddleNode(head);System.out.println(mid.val);ListNode hret = s.sortList(head);while(hret != null){System.out.print(hret.val + " ");hret = hret.next;}//while(head != null)//{//System.out.print(head.val + " ");//head = head.next;//}}}class ListNode{int val;ListNode next;ListNode(int x){val = x;next = null;}}
0 0
- leetcode之时间复杂度为O(nlogn)的链表排序
- 实现时间复杂度为O(nlogn)的链表排序算法
- O(nlogn)时间复杂度 链表排序
- 对链表排序 要求时间 复杂度为 O(nlogn) 空间复杂度为常量
- LeetCode 148. Sort List--O(nlogn)时间复杂度和常数空间复杂度给链表排序
- 排序的最低时间复杂度为什么是O(nlogn)
- 关于快速排序和插入排序最坏时间复杂度为O(nlogn)的算法
- 【项目3 - 体验复杂度之二 复杂度为O(nlogn) 的快速排序quicksort】
- Java-时间复杂度为O(nlogn)的排序算法(快速排序, 归并排序, 堆排序, 希尔排序)
- 堆排序复杂度为O(nlogn),需要注意的误区
- 二、排序(时间复杂度 O(nlogn))
- 归并排序平均时间复杂度O(NlogN)
- 快速排序[平均时间复杂度O(NlogN)]
- 单链表的归并排序:时间复杂度O(nlogn),空间复杂度O(1)
- 每天一道LeetCode-----链表排序,要求复杂度在O(nlogn)
- 时间复杂度为O(n)的排序
- 时间复杂度为O(n)的排序
- 快速排序算法的时间复杂度为什么是O(NlogN),还有O(N^2)
- 数学之路(3)-SVR-支持向量回归
- Leetcode-Reorder List
- UIKit 06、使用UITabBarController 和 自定义标签栏控件 创建多视图的iOS应用程序
- Sony 面经
- 【分享】国家自然科技资源平台实验材料数据库
- leetcode之时间复杂度为O(nlogn)的链表排序
- 如何重用其他项目中的源代码
- Android之Alarm
- errno perrno与strerrno
- 键盘聚焦
- 删除用户和表空间impdp重新导入数据
- linux dos格式unix格式转换
- 开始认真写博客
- 福州八旬翁街头晕倒头破血流 好心市民齐援手