【算法训练】LeetCode#23 合并K个排序链表

一、描述

23. 合并K个升序链表加

给你一个链表数组,每个链表都已经按升序排列。

请你将所有链表合并到一个升序链表中,返回合并后的链表。

示例 1:

输入:lists = [[1,4,5],[1,3,4],[2,6]]
输出:[1,1,2,3,4,4,5,6]
解释:链表数组如下:
[
  1->4->5,
  1->3->4,
  2->6
]
将它们合并到一个有序链表中得到。
1->1->2->3->4->4->5->6

示例 2:

输入:lists = []
输出:[]

示例 3:

输入:lists = [[]]
输出:[]

二、思路

  1. 遍历所有,按升序加到一个新链表结构上,简单粗暴
  2. 方法二是借用小顶堆和比较器,依次入队再出队即完成排序

三、解题

public static class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
public static class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        ListNode ans = new ListNode();
        ListNode head = new ListNode();
        ans = head;
        if (lists == null || lists.length ==0 ){
            return null;
        }

        while (true){
            int minindex = -1; // 每轮最小节点所在链表
            int minValue = Integer.MAX_VALUE; // 当前最小值
            for (int cur = 0 ; cur < lists.length ; cur++){
                if (lists[cur] == null){
                    // 如果某个链表为空
                    continue;
                }
                if (minValue >= lists[cur].val){
                    minindex = cur;
                    minValue = lists[cur].val;
                }
            }
            if (minindex == -1){
                break;
            }
            // 拿到该轮最小节点位置
            head.next = lists[minindex];
            head = head.next;
            lists[minindex] = lists[minindex].next;

        }
        return ans.next;
    }
    public static class Comp implements Comparator<ListNode>{

        @Override
        public int compare(ListNode o1, ListNode o2) {
            return o1.val - o2.val;
        }
    }

    public ListNode mergeKListsV02(ListNode[] lists) {
        ListNode ans = new ListNode();
        ListNode head = new ListNode();
        PriorityQueue<ListNode> queue = new PriorityQueue<>(new Comp());
        ans = head;
        if (lists == null || lists.length ==0 ){
            return null;
        }
        for (int i = 0 ; i < lists.length ; i++){
            while (lists[i] != null){
                queue.add(lists[i]);
                lists[i] = lists[i].next;
            }
        }
        while (!queue.isEmpty()){
            head.next = queue.poll();
            head = head.next;
        }
        head.next = null; // 防止回环
        return ans.next;
    }
}
posted @ 2023-01-01 16:58  小拳头呀  阅读(10)  评论(0编辑  收藏  举报