leetCode练习(148)
2017-03-06 20:38
351 查看
题目:Sort List
难度:MEDIUM
问题描述:
Sort a linked list in O(n log n) time using constant space complexity.
Subscribe to see which companies asked this question.
解题思路:使用归并排序即可。注意模块化。
难度:MEDIUM
问题描述:
Sort a linked list in O(n log n) time using constant space complexity.
Subscribe to see which companies asked this question.
解题思路:使用归并排序即可。注意模块化。
/** * 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) { int len = this.length(head); return guibing(head,len); } private ListNode guibing(ListNode head,int len){ ListNode[] lists; if(len==0){ return head; } if(len==1){ return head; }else{ lists=this.sperate(head,len); lists[0]=guibing(lists[0],len/2); lists[1]=guibing(lists[1],len-len/2); head=concat(lists[0],lists[1]); } return head; } private ListNode concat(ListNode first,ListNode second){ ListNode head=new ListNode(-1); ListNode temp=head; while(first!=null && second!=null){ if(first.val<second.val){ temp.next=first; temp=temp.next; first=first.next; }else{ temp.next=second; temp=temp.next; second=second.next; } } if(first==null){ temp.next=second; }else{ temp.next=first; } return head.next; } private int length(ListNode head){ int len; if(head==null){ len=0; }else{ len = 1; while(head.next!=null){ head = head.next; len++; } } return len; } private ListNode[] sperate(ListNode head,int len){ int mid=len/2; ListNode[] res = new ListNode[2]; ListNode temp=head; for(;mid>1;mid--){ temp=temp.next; } res[1]=temp.next; temp.next=null; res[0]=head; return res; } }
相关文章推荐
- LeetCode Online Judge 题目C# 练习 - Permutations
- LeetCode Online Judge 题目C# 练习 - Regular Expression Matching
- LeetCode Online Judge 题目C# 练习 - Remove Duplicates from Sorted List II
- leetcode练习 Clone Graph
- LeetCode Online Judge 题目C# 练习 - Two Sum
- Leetcode练习<十三> 判断数据的插入位置
- 数据结构与算法 LeetCode编程练习--Delete Node in a Linked List
- LeetCode 148. Sort List
- Leetcode练习<十九> 字符串数组的公共前缀
- leetCode练习(66)
- 英语练习148 Global warming
- Leetcode练习 #3Longest Substring Without Repeating Characters
- leetcode(148):Sort List
- leetCode练习(83)
- leetCode练习(520)
- leetcode练习 Maximum Length of Repeated Subarray
- 『LeetCode』练习第四弹_算法6题
- leetCode练习(91)
- 【leetcode】sql练习
- Leetcode练习-Remove Duplicates from Sorted List