/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode mergeKLists(ArrayList<ListNode> lists) {
if(lists.isEmpty()) return null;
if(lists.size() == 1) return lists.get(0);
// int k = lists.size();
// int log = (int)(Math.log(k)/Math.log(2));
// log = log < Math.log(k)/Math.log(2)? log+1:log; // take ceiling
// for(int i = 1; i <= log; i++){
// for(int j = 0; j < lists.size(); j=j+(int)Math.pow(2,i)){
// int offset = j+(int)Math.pow(2,i-1);
// lists.set(j, mergeTwoLists(lists.get(j), (offset >= lists.size()? null : lists.get(offset))));
// }
// }
int index = lists.size();
while(index > 1){
int remain = index % 2;
int middle = index / 2;
for(int i = 0; i < middle; i++){
lists.set(i + remain, mergeTwoLists(lists.get(i + remain), lists.get(i + middle + remain)));
}
index = middle + remain;
}
return lists.get(0);
}
The idea is to binary merge the list heads in the list, and merge to first half. Notice for remaining case… Take the advantage that eventually the divide will be 1 by add the remaining to the next index each iteration!
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(l1 == null) return l2;
if(l2 == null) return l1;
ListNode head = l1.val > l2.val? l2:l1;
if(head.equals(l1)){
l1 = l2;
l2 = head;
}
while(l2.next != null && l1 != null){
if(l2.next.val > l1.val){
ListNode tmp = l2.next;
l2.next = l1;
l1 = l1.next;
l2 = l2.next;
l2.next = tmp;
}
else
l2 = l2.next;
}
if(l1 != null){
l2.next = l1;
}
return head;
}
}
没有评论:
发表评论