[LeetCode] Merge k Sorted Lists

题目

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

思路

这道题借鉴的是归并排序的思想。前面已经实现了两个链表的合并,把一个链表看成一个元素,模仿归并排序的过程,很容易实现。


代码

<pre name="code" class="java">/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        if (lists == null)
            return null;
            
        int len = lists.length;
        if (len == 0)
            return null;
        if(len == 1)  
            return lists[0];  
            
        int mid = (len - 1)/2 ;  
        ListNode l1 = mergeKLists(Arrays.copyOfRange(lists, 0, mid + 1));  
        ListNode l2 = mergeKLists(Arrays.copyOfRange(lists, mid + 1, len));
        return mergeTwoLists(l1, l2);
    }
    
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if(l1 == null)
            return l2;
        if(l2 == null)
            return l1;
            
        ListNode head = new ListNode(0);
        ListNode curr = head;
        
        while(l1 != null && l2 != null) {
            int num1 = l1.val;
            int num2 = l2.val;
            int num3 = 0;
            
            if (num1 < num2) {
                num3 = num1;
                l1 = l1.next;
            }
            else {
                num3 = num2;
                l2 = l2.next;
            }
            curr.next = new ListNode(num3);
            curr = curr.next;
        }
        
        if (l1 != null)
            curr.next = l1;
        else
            curr.next = l2;
        return head.next;
    }
}
 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值