LeetCode—merge-k-sorted-lists(归并排序链表)—java

本文介绍了一种使用归并排序思想解决合并K个已排序链表问题的方法。通过递归地将链表分为两半,再将每半分别排序并合并,最终实现对所有链表的有效合并。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

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

思路解析

  • 归并排序是排列数组的,现在应用到排列list

这里来复习一下Merge Sort(对于数组操作),参考Wikipedia:

归并操作(merge),也叫归并算法,指的是将两个已经排序的序列合并成一个序列的操作。归并排序算法依赖归并操作。

归并操作的过程如下:

  1. 申请空间,使其大小为两个已经排序序列之和,该空间用来存放合并后的序列
  2. 设定两个指针,最初位置分别为两个已经排序序列的起始位置
  3. 比较两个指针所指向的元素,选择相对小的元素放入到合并空间,并移动指针到下一位置
  4. 重复步骤3直到某一指针到达序列尾
  5. 将另一序列剩下的所有元素直接复制到合并序列尾

参考:https://www.cnblogs.com/springfor/p/3869217.html

代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
import java.util.*;
public class Solution {
    public ListNode mergeKLists(ArrayList<ListNode> lists) {
        if(lists==null || lists.size()==0)
            return null;
        return Msort(lists,0,lists.size()-1);
    }
    public ListNode Msort(ArrayList<ListNode> lists,int low,int high){
        if(low<high){
            int mid = (low+high)/2;
            ListNode leftlist = Msort(lists,low,mid);
            ListNode rightlist = Msort(lists,mid+1,high);
            return MergeTwoLists(leftlist,rightlist);
        }
        return lists.get(low);
    }
    public ListNode MergeTwoLists(ListNode l1,ListNode l2){
        if(l1==null)
            return l2;
        if(l2==null)
            return l1;
        ListNode l3;
        ListNode fakehead = new ListNode(-1);
        if(l1.val<l2.val){
            l3=l1;
            l1=l1.next;
        }
        else{
            l3 =l2;
            l2=l2.next;
        }
        fakehead.next=l3;
        while(l1!=null && l2!=null){
            if(l1.val<l2.val){
                l3.next = l1;
                l3 = l3.next;
                l1 = l1.next;
            }else{
                l3.next = l2;
                l3=l3.next;
                l2=l2.next;
            }
        }
        if(l1!=null){
            l3.next = l1;
        }
        if(l2!=null){
            l3.next = l2;
        }
        return fakehead.next;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值