首页 > 代码库 > leetcode : merge k sorted list

leetcode : merge k sorted list

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

 

 

两种方法: 

(1) 类似于归并排序,把链表数组分割成两两最小的链表对(可能存在落单的情况,要做处理), 再调用merge two sorted lists 方法

(2) 类似于堆排序的思路。 (尚未实践)。 comparator   priorityqueue

 

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        if(lists == null){
            return null;
        }
        return mergeLists(lists,0,lists.length - 1);
    }
    
    public ListNode mergeLists(ListNode[] lists,int start, int end){
        
        if(lists == null || lists.length == 0){
            return null;
        }
        
        if(start == end){
            return lists[start];
        }
        
        int mid = start + (end - start) / 2;
        ListNode left = mergeLists(lists,start,mid);
        ListNode right = mergeLists(lists,mid + 1,end);
        return mergeTwoLists(left,right);
    }
    
    public ListNode mergeTwoLists(ListNode l1, ListNode l2){
        
           if(l1 == null && l2 == null){
			return null;
		}
		
		if(l1 == null){
			return l2;
		}
		
		if(l2 == null){
			return l1;
		}
        ListNode dummy = new ListNode(0);
        ListNode cur = dummy;
        
        while(l1 != null && l2 != null){
            if(l1.val < l2.val){
                cur.next = l1;
                l1 = l1.next;
            }else{
                cur.next = l2;
                l2 = l2.next;
            }
            cur = cur.next;
        }
        
        if(l1 != null){
            cur.next = l1;
        }
        if(l2 != null){
            cur.next = l2;
        }
        
        return dummy.next;
    }
    
}

  

 

leetcode : merge k sorted list