LeetCode 23. 合并K个升序链表

LeetCode 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

LeetCode 23. 合并K个升序链表
提示:


一、解题关键词

链表已经有顺序,两个链表合并的升级版

二、解题报告

1.思路分析

拆分list,进行两个list的合并

2.时间复杂度

3.代码示例

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        //归并排序
        int len = lists.length;
        ListNode result = null;
        for(int i = 0;i<len;i++){
            result = mergeTwoList(result,lists[i]);
        }
        return result;
    }
    ListNode mergeTwoList(ListNode node1,ListNode node2){
        if(node1 == null || node2 == null){
            return node1 != null ? node1 : node2;
        }
        ListNode head = new ListNode(0);
        ListNode tail = head,aptr = node1,bprt = node2;
        while(aptr != null && bprt != null){
            if(aptr.val < bprt.val){
                tail.next = aptr;
                aptr = aptr.next;
            }else{
                tail.next = bprt;
                bprt = bprt.next;
            }
            tail = tail.next;
        }
        tail.next = (aptr != null ? aptr:bprt);
        return head.next;
    }
}

2.知识点

归并排序

总结

归并吧 链表!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大涛小先生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值