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;
    }
    
}

  

 

转载于:https://www.cnblogs.com/superzhaochao/p/6400646.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值