Sort List (LeetCode)
来源:互联网 发布:手机天文软件 编辑:程序博客网 时间:2024/05/21 17:01
Sort a linked list in O(n log n) time using constant space complexity.
看到 O(nlogn)第一想到的是merge sort,这里采用的是每次merge前遍历当前list,找到中间节点,然后对head和中间节点分别再进行sort,再merge。
或者也可以用两个point,start和end,当start==end时,到了base case,return当前node,不过仍要遍历list以获取start所在节点的位置。
public ListNode sortList(ListNode head) { if(head==null||head.next==null) return head; ListNode slow = head, fast = head; while(fast.next!=null && fast.next.next!=null){ slow=slow.next; fast=fast.next.next; } fast=slow.next; slow.next=null; slow = sortList(head); fast = sortList(fast); return merge(slow,fast); } public ListNode merge(ListNode l1, ListNode l2){ if(l1==null||l2==null) return l1==null? l2 : l1; ListNode head = null, run = null; if(l1.val>l2.val){ head = l2; l2=l2.next; } else{ head = l1; l1=l1.next; } run = head; while(l1!=null && l2!=null){ if(l1.val<l2.val){ run.next=l1; run=run.next; l1=l1.next; } else{ run.next=l2; run=run.next; l2=l2.next; } } if(l1!=null) run.next=l1; else if(l2!=null) run.next=l2; return head; }
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
- HDU 4529 郑厂长系列故事——N骑士问题(dp,状态压缩)
- ood
- Insertion Sort List (LeetCode)
- 2014年1月14日(DEMO7-2,加载PLG)
- Evaluate Reverse Polish Notation (LeetCode)
- Sort List (LeetCode)
- [CrackCode] 1.4 Write a method to decide if two strings are anagrams or not
- 鼠标右键
- HDU 4549 M斐波那契数列 (费马小定理降幂&矩阵快速幂)
- Reorder List (LeetCode)
- 已知递推式求第N项的O(logN)算法 (递推式转化为矩阵)
- 同步方法和lock的区别
- css常用属性
- quicksort