【LeetCode】Sort List
来源:互联网 发布:淘宝入门视频教程 编辑:程序博客网 时间:2024/06/06 14:00
Sort List
Total Accepted: 22650 Total Submissions: 110501My SubmissionsSort a linked list in O(n log n) time using constant space complexity.
因为要求是O(n log n),所以选择用归并排序的方法。但因为是linked list,所以需要先找出中点的位置。可以采用两个指针,一个每次移动两步,一个每次移动一步,当快指针走到底的时候,满指针刚好走到中间。
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { public ListNode sortList(ListNode head) { if(head==null||head.next==null) return head; //if(head.next == null) return head; ListNode fast = head; ListNode slow = head; while(fast.next!=null&&fast.next.next!=null){ fast = fast.next.next; slow = slow.next; } ListNode mid = slow.next; slow.next = null; ListNode result = merge(sortList(head),sortList(mid)); return result; } ListNode merge(ListNode left,ListNode right) { ListNode result = new ListNode(0); ListNode tmp = result; while(left!=null&&right!=null) { if(left.val < right.val) { tmp.next = left; tmp = tmp.next; left = left.next; } else { tmp.next = right; tmp = tmp.next; right = right.next; } } if(left== null) { tmp.next = right; } else { tmp.next = left; } return result.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
- 【网络流】 HDU 1569 方格取数(2)
- ZYRBTQQ686
- HYYFUMF846
- The user specified as a definer ('root'@'%') does not exist
- 『IOS』IOS UIView touch事件 详解
- 【LeetCode】Sort List
- axure快捷键!
- Open Lectures
- git命令
- java实现和电脑猜随机数生成1到100
- hdu 2059 dp
- 开始写博客了
- Axure RP 7.0快捷键
- Shuttle ESB(五)——发布订阅模式实例实现(2)