leetcode解题之23.Merge k Sorted Lists Java版本(合并k个有序的链表)

23. Merge k Sorted Lists

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

合并k个有序的链表

归并排序参考

合并两个有序的链表参考

public ListNode mergeKLists(ListNode[] lists) {
		if (lists == null || lists.length == 0)
			return null;
		return MSort(lists, 0, lists.length - 1);
	}

	public ListNode MSort(ListNode[] lists, int low, int high) {
		if (low < high) {
			int mid = (low + high) / 2;
			ListNode leftlist = MSort(lists, low, mid);
			ListNode rightlist = MSort(lists, mid + 1, high);
			return mergeTwoLists(leftlist, rightlist);
		}
		// 如果相等,只有一个元素,返回即可
		return lists[low];
	}

	// 递归合并链表
	public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
		ListNode res = null;
		if (l1 == null)
			return l2;
		if (l2 == null)
			return l1;
		if (l1.val <= l2.val) {
			res = l1;
			l1.next = mergeTwoLists(l1.next, l2);
		} else {
			res = l2;
			l2.next = mergeTwoLists(l1, l2.next);
		}
		return res;
	}

使用小顶堆

public ListNode mergeKLists(ListNode[] lists) {
		if (lists == null || lists.length == 0)
			return null;
		// PriorityQueue 是堆,默认小顶堆
		PriorityQueue<ListNode> min = new PriorityQueue<ListNode>(11, new Comparator<ListNode>() {
			@Override
			public int compare(ListNode o1, ListNode o2) {
				return o1.val - o2.val;
			}
		});
		// 加入所有链表的第一个结点,非空
		for (ListNode node : lists)
			if (node != null)
				min.offer(node);
		ListNode head = new ListNode(0);
		ListNode cur = head;
		while (!min.isEmpty()) {
			ListNode temp = min.poll();
			cur.next = temp;
			cur = cur.next;
			// 边取边加入
			if (temp.next != null)
				min.offer(temp.next);
		}
		// 注意断链
		cur.next = null;
		return head.next;
	}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值