码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode]merge-k-sorted-lists

时间:2018-09-26 11:46:15      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:int   com   div   des   ted   合并   复杂   描述   linked   

题目描述:Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

题目理解:合并k个有序表成为一个有序表

简单版:简单遍历

代码:

1 public ListNode mergeKLists(ArrayList<ListNode> lists){
2         if(lists.size() == 0) return null;
3         ListNode head = lists.get(0);
4         for (int i = 1; i < lists.size(); i ++ )
5             head = mergeTwoList(head, lists.get(i));
6         return head;
7     }

晋级版:归并法(时间复杂度nlogk)二二合并

代码:

 1 public ListNode mergeKlists2(ArrayList<ListNode> lists){
 2         if(lists == null || lists.size() == 0) return null;
 3         return mergeLists(lists,0,lists.size()-1);
 4     }
 5 
 6     public ListNode mergeLists(ArrayList<ListNode> lists, int low, int high) {
 7         if(high <= low) return lists.get(low);
 8         int mid = low+(high-low)/2;
 9         ListNode left = mergeLists(lists,low,mid);
10         ListNode right = mergeLists(lists,mid+1,high);
11         return mergeTwoList(left,right);
12     }

公用代码:

 1 public ListNode mergeTwoList(ListNode one,ListNode two){
 2         ListNode list = new ListNode(-1);
 3         ListNode tmp = list;
 4         while(one != null && two != null){
 5             if(one.val < two.val){
 6                 tmp.next = one;
 7                 one = one.next;
 8             }else{
 9                 tmp.next = two;
10                 two = two.next;
11             }
12             tmp = tmp.next;
13         }
14         if(one != null) tmp.next = one;
15         if(two != null) tmp.next = two;
16         return list.next;
17     }

 

[leetcode]merge-k-sorted-lists

标签:int   com   div   des   ted   合并   复杂   描述   linked   

原文地址:https://www.cnblogs.com/whl-shtudy/p/9705802.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!