【leetcode】23. Merge k Sorted Lists
2016-07-05 00:34
246 查看
题目描述:
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
解题分析:
解题思路很简单,就是先两两排序,不断减小链表数量,最后将所有数组织成一个有序链表
具体代码:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public static ListNode mergeKLists(ListNode[] lists) { if(lists.length==0) return null; if(lists.length==1) return lists[0]; int from=0; int to=lists.length-1; //两两排序时使用类似二分查找的方法缩小时间复杂度 while(from!=to){ //from+to等于偶数 if(((from+to)&1)==0){ int mid=(from+to)>>1; for(int i=0;i<mid;i++){ lists[i]=mergeTwoLists(lists[i], lists[mid+1+i]); } to=mid; } else{ int mid=(from+to)>>1; for(int i=0;i<=mid;i++){ lists[i]=mergeTwoLists(lists[i], lists[mid+1+i]); } to=mid; } } return lists[0]; } //和并两个链表的方法 public static ListNode mergeTwoLists(ListNode head1, ListNode head2) { if(head1==null) return head2; if(head2==null) return head1; ListNode head=null; ListNode current=null; if(head1.val<=head2.val){ head=head1; head1=head1.next; head.next=null; } else{ head=head2; head2=head2.next; head.next=null; } current=head; while(head1!=null&&head2!=null){ if(head1.val<=head2.val){ current.next=head1; current=current.next; head1=head1.next; current.next=null; } else{ current.next=head2; current=current.next; head2=head2.next; current.next=null; } } if(head1!=null){ current.next=head1; } if(head2!=null){ current.next=head2; } return head; } }
相关文章推荐
- LeetCode | 23. Merge k Sorted Lists
- 23. Merge k Sorted Lists python leetcode 2016 new Season
- leetcode 23. Merge k Sorted Lists
- leetcode23. Merge k Sorted Lists
- LeetCode 23. Merge k Sorted Lists
- leetcode--23. Merge k Sorted Lists
- leetcode23. Merge k Sorted Lists总结
- [LeetCode]23. Merge k Sorted Lists
- 【leetcode】23. Merge k Sorted Lists
- Leetcode: Merge k Sorted Lists
- leetcode--Merge k Sorted Lists
- LeetCode Merge k Sorted Lists
- LeetCode编程练习 - Merge Two Sorted Lists学习心得
- leetcode: Merge k Sorted Lists
- leetcode--Merge Two Sorted Lists
- LeetCode Merge k Sorted Lists 解决报告
- LeetCode 21. Merge Two Sorted Lists
- 23. Merge k Sorted Lists
- Merge k Sorted Lists(leetcode)
- 【LeetCode 21】Merge Two Sorted Lists(Python)