• 【Leetcode】23. Merge k Sorted Lists


    Question:

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

    Tips:

    将k个有序的链表合并成为一个有序链表。

    思路:

    这个题目是将两个链表合并为一个有序链表的升级版本。我的思想还是,两个两个的合并。每次只合并两个链表。

    代码:

    public ListNode mergeKLists(ListNode[] lists) {
            if (lists.length == 0)
                return null;
            if (lists.length == 1)
                return lists[0];
            return partion(lists, 0, lists.length - 1);
        }
    
        // 将ListNode数组两两分为一组,调用merge函数
        private ListNode partion(ListNode[] lists, int i, int j) {
            if (i == j)
                return lists[i];
            if (i < j) {
                int temp = (i + j) / 2;
                ListNode l1 = partion(lists, i, temp);
                ListNode l2 = partion(lists, temp + 1, j);
                return merge(l1, l2);
            } else {
                return null;
            }
        }
    
        // 合并两个链表
        private ListNode merge(ListNode l1, ListNode l2) {
            if (l1 == null)
                return l2;
            if (l2 == null)
                return l1;
            ListNode dummy = new ListNode(-1);
            ListNode head = dummy;
            while (l1 != null && l2 != null) {
                if (l1.val <= l2.val) {
                    dummy.next = l1;
                    l1 = l1.next;
                } else {
                    dummy.next = l2;
                    l2 = l2.next;
                }
                dummy = dummy.next;
            }
            while (l1 != null) {
                dummy.next = l1;
                l1 = l1.next;
                dummy = dummy.next;
            }
            while (l2 != null) {
                dummy.next = l2;
                l2 = l2.next;
                dummy = dummy.next;
            }
    
            return head.next;
        }
  • 相关阅读:
    python 按行读取判断是否为空
    python获取目录下所有文件
    Kolakoski
    最小背包问题
    python 求第k个最大数
    python 求最大子序列
    爬取数据的程序
    文件对比程序
    trsd_extract_EDSD_new
    tred_extract_EDED_new
  • 原文地址:https://www.cnblogs.com/yumiaomiao/p/8507556.html
Copyright © 2020-2023  润新知