美文网首页
LeetCode每日一题:merge k sorted list

LeetCode每日一题:merge k sorted list

作者: yoshino | 来源:发表于2017-07-04 16:07 被阅读20次

    问题描述

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

    问题分析

    我们可以使用以前写过的合并两条有序链表mergeTwoLists()函数,循环k次即可,复杂度是O(n*k)=O(n^2)。

    代码实现

    public ListNode mergeKLists(ArrayList<ListNode> lists) {
            if (lists.size() == 0) return null;
            ListNode head = lists.get(0);
            for (int i = 1; i < lists.size(); i++) {
                head = mergeTwoLists(head, lists.get(i));
            }
            return head;
        }
        public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            ListNode head = new ListNode(0);
            ListNode cur = head;
            while (l1 != null && l2 != null) {
                if (l1.val <= l2.val) {
                    cur.next = l1;
                    l1 = l1.next;
                } else {
                    cur.next = l2;
                    l2 = l2.next;
                }
                cur = cur.next;
            }
            if (l1 == null) {
                cur.next = l2;
            }
            if (l2 == null) {
                cur.next = l1;
            }
            return head.next;
        }
    

    相关文章

      网友评论

          本文标题:LeetCode每日一题:merge k sorted list

          本文链接:https://www.haomeiwen.com/subject/zdrxhxtx.html