【重点】23.合并K个升序链表

2023-12-15 05:02:39

题目

法1:分治合并

在这里插入图片描述

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

    public ListNode merge(ListNode[] lists, int l, int r) {
        if (l > r) {
            return null;
        }
        if (l == r) {
            return lists[l];
        }
        int mid = l + (r - l) / 2;
        return merge2List(merge(lists, l, mid), merge(lists, mid + 1, r));
    }

    public ListNode merge2List(ListNode first, ListNode second) {
        ListNode dummy = new ListNode(-1);
        ListNode tmp = dummy;
        while (first != null && second != null) {
            if (first.val <= second.val) {
                tmp.next = first;
                first = first.next;
            } else {
                tmp.next = second;
                second = second.next;
            }
            tmp = tmp.next;
        }
        if (first == null) {
            tmp.next = second;
        }
        if (second == null) {
            tmp.next = first;
        }

        return dummy.next;
    }
}

法2:其他

在这里插入图片描述

class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        if (lists.length == 0) {
            return null;
        }
        if (lists.length == 1) {
            return lists[0];
        }
        ListNode merged = lists[0];
        for (int i = 1; i < lists.length; ++i) {
            merged = merge(merged, lists[i]);
        }

        return merged;
    }

    public ListNode merge(ListNode first, ListNode second) {
        ListNode dummy = new ListNode(-1);
        ListNode tmp = dummy;
        while (first != null && second != null) {
            if (first.val <= second.val) {
                tmp.next = first;
                first = first.next;
            } else {
                tmp.next = second;
                second = second.next;
            }
            tmp = tmp.next;
        }
        if (first == null) {
            tmp.next = second;
        }
        if (second == null) {
            tmp.next = first;
        }

        return dummy.next;
    }
}

文章来源:https://blog.csdn.net/Allenlzcoder/article/details/135007267
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。