[Leetcode] 23. Merge k Sorted Lists

原创 2016年06月02日 10:28:27

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

思路:
一看到这个题目,开始的想法是依次将两个已有顺序链表的合并。但是这个方法,如果数组长度是n,合并次数就是n次,运行超时。
所以要减少链表之间的合并次数。
可以利用归并的思想。

具体代码如下:

/**
 * 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 merge(lists, 0, lists.length);
    }

    public ListNode merge(ListNode[] lists,int low, int high){
        int n = high - low;
        if(n < 1){
            return null;
        }
        if(n == 1){
            return lists[low];
        }
        int mid = low + n / 2;

        ListNode left = merge(lists,low, mid);
        ListNode right = merge(lists,mid, high);

        return MegerList(left,right);
    }

//  对两个已排序的链表进行合并
    public ListNode MegerList(ListNode head1,ListNode head2){
        ListNode phead = new ListNode(Integer.MIN_VALUE);
        ListNode p = phead;

        while(head1 != null && head2 != null){
            if(head1.val < head2.val){
                p.next = head1;
                head1 =head1.next;
            }
            else{
                p.next = head2;
                head2 =head2.next;
            }
            p = p.next;
        }

        if(head1 != null){
            p.next = head1;
        }
        if(head2 != null){
            p.next = head2;
        }

        return phead.next;
    }
}
版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

leetcode23~Merge k Sorted Lists Add to List

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

【leetcode】23. Merge k Sorted Lists

合并多个已排序的单链表,多种实现方式

[leetcode] 23. Merge k Sorted Lists

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

leetcode_23_Merge k Sorted Lists

思路: 本来想模仿合并两个链表的方法,查找所有的lists链表一遍找出一个最小值,并将最小值链接到结果链表中,并将最小结点删除,将最小结点的next结点替代之,直至为null,将链表删去。 但是当l...

LeetCode_OJ【23】Merge k Sorted Lists

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

leetcode--23. Merge k Sorted Lists

leetcode

leetcode23---Merge k Sorted Lists

问题描述:有k个已经排好序的链表,将其合并为一个有序链表。代码:#include #include #include using namespace std;struct ListNode { ...

LeetCode 23 Merge k Sorted Lists

这是一道基本的归并排序问题,设定步长d初始为1,然后以指数增长归并向量元素 每次归并的思想就是将后一个链表的元素插入前一个链表,如果前一个链表为空,则前一个链表直接指向后一个链表 当d大于...

Leetcode-23.Merge k Sorted Lists

Problem Description: Merge k sorted linked lists and return it as one sorted list. Analyze and desc...

leetcode23. Merge k Sorted Lists

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. ...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)