[leetcode]merge-k-sorted-lists
Posted whl-shtudy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode]merge-k-sorted-lists相关的知识,希望对你有一定的参考价值。
题目描述: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的主要内容,如果未能解决你的问题,请参考以下文章