23 Merge N Sorted Lists

复习一下这道题。我一直都是用merge sort解法做的。今天在搜索别的解法时,发现这个文章讲的非常好: http://bangbingsyb.blogspot.com/2014/11/leetcode-merge-k-sorted-lists.html. 我的解法应该是属于第三种, time complexity nklog(k)

public class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        if (lists == null || lists.length == 0) {
            return null;
        }

        return MSort(lists, 0, lists.length - 1);
    }

    public ListNode MSort(ListNode[] lists, int start, int end) {
        if (start < end) {
            int mid = start + (end - start) / 2;
            ListNode left = MSort(lists, start, mid);
            ListNode right = MSort(lists, mid + 1, end);
            return mergeTwoLists(left, right);
        }
        return lists[start];
    }

    public ListNode mergeTwoLists(ListNode left, ListNode right) {
        if (left == null && right == null) {
            return null;
        } else if (left == null) {
            return right;
        } else if (right == null) {
            return left;
        }

        ListNode dummy = new ListNode(0);
        ListNode head = dummy;

        while (left != null && right != null) {
            if (left.val > right.val) {
                head.next = right;
                right = right.next;
            } else {
                head.next = left;
                left = left.next;
            }
            head = head.next;
        }

        if (left != null) {
            head.next = left;
        } else if (right != null) {
            head.next = right;
        }

        return dummy.next;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值