[leetcode]Merge k Sorted Lists

本文详细介绍了如何在LeetCode上解决合并K个排序链表的问题,并深入分析了该算法的时间复杂度。通过使用优先级队列实现高效的合并过程,确保了整体解决方案的效率。

https://leetcode.com/problems/merge-k-sorted-lists/

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

/**
 * 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) {
		PriorityQueue<ListNode> heap = new PriorityQueue<ListNode>(10,
				new Comparator<ListNode>() {
					@Override
					public int compare(ListNode n1, ListNode n2) {
						return n1.val - n2.val;
					}
				}
		);
		
		for (int i = 0, ln = lists.length; i < ln; ++i) {
			ListNode node = lists[i];
			if (node != null) {
				heap.offer(node);
			}
		}
		ListNode head = null, pre = null;
		while (0 < heap.size()) {
			ListNode cur = heap.poll();
			if (head == null) {
				head = cur;
				pre = head;
			} else {
				pre.next = cur;
			}
			pre = cur;
			if (cur.next != null)
				heap.offer(cur.next);
		}
		return head;
	}
}

/**
 * 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(null == lists || 0 == lists.length) {
            return null;
        }
        int n = lists.length;
        while(1 < n) {
            for(int i=0, k=n>>1; i<k; ++i) {
                lists[i] = merge(lists[i], lists[i+k]);
            }
            if(0 != (n&1)) {
                lists[n>>1] = lists[n-1];
                n = (n>>1) + 1;
            } else {
                n = n>>1;
            }
        }
        return lists[0];
	}
	
	private ListNode merge(ListNode l1, ListNode l2) {
	    ListNode dy = new ListNode(0), p=dy;
	    while(null != l1 && null != l2) {
	        if(l1.val < l2.val) {
	            p.next = l1;
	            p = l1;
	            l1 = l1.next;
	        } else {
	            p.next = l2;
	            p = l2;
	            l2 = l2.next;
	        }
	    }
	    if(null != l1) {
	        p.next = l1;
	        p = l1;
	        l1 = l1.next;
	    }
	    if(null != l2) {
	        p.next = l2;
	        p = l2;
	        l2 = l2.next;
	    }
	    
	    return dy.next;
	}
}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值