---
title: "Merge k Sorted Lists"
author: "KickCode"
date: "2016-03-07T04:03:59Z"
tags: []
categories: ["编程语言"]
slug: "merge-k-sorted-lists"
draft: false
lastmod: "2016-03-07T04:03:59Z"
id: 2280991
url: "https://kickcode.iteye.com/blog/2280991"
---

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

Merge k个有序链表，之前做过一道题目是merge两个有序的链表，这里我们用分治的思想，用归并排序解决。先将k个链表递归的分为两部分，直到剩下两个链表，然后将两个链表合并起来。因为有k个list，假设每个list中有n个元素，那么时间复杂度为O(nk*logk). 代码如下:

```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 || lists.length == 0) return null;
        return helper(0, lists.length - 1, lists);
    }
    
    private ListNode helper(int l, int r, ListNode[] lists) {
        if(l < r) {
            int m = l + (r - l) / 2;
            return merge(helper(l, m, lists), helper(m + 1, r, lists));
        }
        return lists[l];
    }
    private ListNode merge(ListNode l1, ListNode l2) {
        if(l1 == null) return l2;
        if(l2 == null) return l1;
        ListNode helper = null;
        if(l1.val > l2.val) {
            helper = l2;
            helper.next = merge(l1, l2.next);
        } else {
            helper = l1;
            helper.next = merge(l1.next, l2);
        }
        return helper;
    }
}

```