LeetCode刷题笔录Merge k Sorted Lists

本文详细介绍了如何使用优先队列合并多个已排序链表为一个有序链表的过程,时间复杂度为O(nklogk),其中n为元素总数,k为链表数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

用一个priority queue,先把每个list的第一个node放进去。每次拿一个node出来,并把node.next放进去。事实上排序是由heap来做的,感觉像是作弊的样子。时间复杂度O(nklogk)。n是元素总数。

/**
 * 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(List<ListNode> lists) {
    	Comparator<ListNode> comparator = new Comparator<ListNode>() {
			@Override
			public int compare(ListNode o1, ListNode o2) {
				return o1.val - o2.val;
			}
		};
        PriorityQueue<ListNode> queue = new PriorityQueue<ListNode>(50, comparator);
        for(ListNode node : lists){
        	if(node != null)
        		queue.offer(node);
        }
        
        ListNode head = null;
        ListNode pre = null;
        while(!queue.isEmpty()){
        	ListNode node = queue.poll();
        	if(head == null){
        		head = node;
        		pre = node;
        	}
        	else{
        		pre.next = node;
        	}
        	
        	pre = node;
        	if(node.next != null){
        		queue.offer(node.next);
        	}
        }
        
        return head;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值