leetcode 23. 合并K个排序链表

leetcode 23. 合并K个排序链表


题意

合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。


解题思路

先定义mergeTwoLists函数,该函数使用归并排序lists1lists2 两个链表进行排序,得到一个新的链表 lists3 。对 lists 中的链表进行两两排序,最终得到一个排好序的链表。


代码
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        int num = lists.length;
        if (num == 0)
        {
            return null;
        }
        
        while (num > 1)
        {
            int k = (num + 1) / 2;
            for (int i = 0; i < num / 2; i++)
            {
                lists[i] = mergeTwoLists(lists[i], lists[i + k]);
            }
            num = k;
        }
        return lists[0];
    }
    
    private ListNode mergeTwoLists(ListNode lists1, ListNode lists2)
    {
        ListNode lists3 = new ListNode(0);
        ListNode cur = lists3;
        ListNode l1 = lists1;
        ListNode l2 = lists2;
        
        while (l1 != null || l2 != null)
        {
            if (l1 == null)
            {
                ListNode nextNode = new ListNode(l2.val);
                cur.next = nextNode;
                cur = cur.next;
                l2 = l2.next;
                continue;
            }
            if (l2 == null)
            {
                ListNode nextNode = new ListNode(l1.val);
                cur.next = nextNode;
                cur = cur.next;
                l1 = l1.next;
                continue;
            }
            
            if (l1.val < l2.val)
            {
                ListNode nextNode = new ListNode(l1.val);
                cur.next = nextNode;
                cur = cur.next;
                l1 = l1.next;
            }
            else
            {
                ListNode nextNode = new ListNode(l2.val);
                cur.next = nextNode;
                cur = cur.next;
                l2 = l2.next;
            }
        }
        
        lists3 = lists3.next;
        return lists3;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值