力扣hot100 合并k个升序链表 K指针 小根堆 递归

Problem: 23. 合并 K 个升序链表
力扣hot100 合并k个升序链表 K指针 小根堆 递归_第1张图片

java没有引用传递

‍ 参考大佬题解

小根堆版

class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        Queue<ListNode> pq = new PriorityQueue<>((v1, v2) -> v1.val - v2.val);
        for (ListNode node: lists) {
            if (node != null) {
                pq.offer(node);
            }
        }

        ListNode dummyHead = new ListNode(0);
        ListNode tail = dummyHead;
        while (!pq.isEmpty()) {
            ListNode minNode = pq.poll();
            tail.next = minNode;
            tail = minNode;
            if (minNode.next != null) {
                pq.offer(minNode.next);
            }
        }

        return dummyHead.next;
    }
}

K指针版

class Solution {
    public ListNode mergeKLists(ListNode[] lists) { 
        int k = lists.length;
        ListNode dummyHead = new ListNode(0);
        ListNode tail = dummyHead;
        while (true) {
            ListNode minNode = null;
            int minPointer = -1;
            for (int i = 0; i < k; i++) {
                if (lists[i] == null) {
                    continue;
                }
                if (minNode == null || lists[i].val < minNode.val) {
                    minNode = lists[i];
                    minPointer = i;
                }
            }
            if (minPointer == -1) {
                break;
            }
            tail.next = minNode;
            tail = tail.next;
            lists[minPointer] = lists[minPointer].next;
        }
        return dummyHead.next;
    }
}

暴力两两合并版

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
	public static ListNode mergeKLists(ListNode[] lists)
	{
		int n = lists.length;
		if (n == 0)
			return null;
		ListNode ans = null;
		for (int i = 0; i < n; i++)
			ans = merge(ans, lists[i]);
		return ans;
	}

	private static ListNode merge(ListNode a, ListNode b)
	{
		ListNode dummy = new ListNode();
		ListNode t = dummy;
		while (a != null && b != null)
		{
			if (a.val < b.val)
			{
				t.next = a;
				a = a.next;
			} else
			{
				t.next = b;
				b = b.next;
			}
			t = t.next;
		}
		t.next = a != null ? a : b;
		return dummy.next;
	}
}

两两合并 递归版

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

    private ListNode merge(ListNode[] lists, int lo, int hi) {
        if (lo == hi) {
            return lists[lo];
        }
        int mid = lo + (hi - lo) / 2;
        ListNode l1 = merge(lists, lo, mid);
        ListNode l2 = merge(lists, mid + 1, hi);
        return merge2Lists(l1, l2);
    }
}

你可能感兴趣的:(力扣,hot100,leetcode,链表,算法)