题解 | 牛群的合并

牛群的合并

https://www.nowcoder.com/practice/d0cb24e1494e4f45a4b7d1a17db0daef

  1. 2路归并

import java.util.*;

public class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }
        ListNode guard = new ListNode(0);
        ListNode t = guard;
        while (l1 != null && l2 != null) {
            if (l2.val < l1.val) {
                t.next = l2;
                l2 = l2.next;
            } else {
                t.next = l1;
                l1 = l1.next;
            }
            t = t.next;
        }
        if (l1 != null) {
            t.next = l1;
        } else {
            t.next = l2;
        }
        return guard.next;
    }

    public ListNode mergeKListsHelper(ListNode[] lists, final int l, final int r) {
        if (l == r) {
            return lists[l];
        }
        if (l > r) {
            return null;
        }

        final int m = l + ((r - l) >> 1);
        return mergeTwoLists(mergeKListsHelper(lists, l, m), mergeKListsHelper(lists, m + 1, r));

    }

    public ListNode mergeKLists (ListNode[] lists) {
        return mergeKListsHelper(lists, 0, lists.length - 1);
    }
}

  1. PriorityQueue 的用法。

import java.util.*;

public class Solution {
    public ListNode mergeKLists (ListNode[] lists) {
        if (lists == null || lists.length == 0) {
            return null;
        }
        
        Comparator<ListNode> nodeComparator = (o1, o2) -> o1.val - o2.val;
        PriorityQueue<ListNode> minHeap = new PriorityQueue<>(lists.length, nodeComparator);
        for (ListNode list: lists) {
            if (list != null) {
                minHeap.add(list);
            }
        }

        ListNode guard = new ListNode(0);
        ListNode t = guard;
        while (!minHeap.isEmpty()) {
            ListNode node = minHeap.poll();
            if (node.next != null) {
                minHeap.add(node.next);
            }
            t.next = node;
            t = t.next;
        }
        return guard.next;
    }

全部评论

相关推荐

2025-12-18 21:55
济宁学院 Java
程序员花海:实习和校招简历正确格式应该是教育背景+实习+项目经历+个人评价 其中项目经历注意要体现业务 实习经历里面的业务更是要自圆其说 简历模板尽可能保持干净整洁 不要太花哨的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务