[LeetCode] 023. Merge k Sorted Lists (Hard) (C++/Python)

索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql)

Github: https://github.com/illuz/leetcode


023. Merge k Sorted Lists (Hard)

链接

题目:https://oj.leetcode.com/problems/merge-k-sorted-lists/

代码(github):https://github.com/illuz/leetcode

题意

021. Merge Two Sorted Lists (Easy) 类似,这次要 Merge K 个。

分析

很明显可以想到利用已经完成的 Merge Two Sorted Lists 的函数来用。

这时有两种方法:

1. (C++) 用二分的思想,把每个 List 和它相邻的 List 进行 Merge,这样规模就缩小了一半了,再重复这样,就可以 O(nklogk) 完成。比如: [1, 2, …, n] 的第一轮 Merge 是 [1, n/2], [2, n/2+1], …

2. (Python) 也是用二分的思想,就是把 Lists 分为两部分,分别递归 Merge k Sorted Lists 后变成两个 List ,然后再对这两 List 进行 Merge Two Sorted Lists 。

这两种方法都是递归调用,都可以进行记忆化,用空间换时间,不过我不清楚会不会超空间(Memory Limit Exceed),所以就没试了~

除了用二分的思路,还有更好写的方法,就是用堆(heap),具体就是用优先队列(Priority Queue)。

(Java) 先把每个 List 的第一个节点放进优先队列,每次取出队列中的最大值节点,再把那个节点的 next 放进去。

代码

C++:

class Solution {
public:
    ListNode *mergeKLists(vector<ListNode *> &lists) {
		int sz = lists.size();
		if (sz == 0)
			return NULL;

		while (sz > 1) {
			int k = (sz + 1) / 2;
			for (int i = 0; i < sz / 2; i++)
				lists[i] = mergeTwoLists(lists[i], lists[i + k]);
			sz = k;
		}
		return lists[0];
	}

    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
		if (l1 == NULL)
			return l2;
		if (l2 == NULL)
			return l1;

		ListNode *start, *p1;

		if (l1->val < l2->val) {
			p1 = start = l1;
			l1 = l1->next;
		} else {
			p1 = start = l2;
			l2 = l2->next;
		}
		while (l1 != NULL && l2 != NULL) {
			if (l1->val < l2->val) {
				p1->next = l1;
				p1 = l1;
				l1 = l1->next;
			} else {
				p1->next = l2;
				p1 = l2;
				l2 = l2->next;
			}
		}
		if (l1 != NULL)
			p1->next = l1;
		else
			p1->next = l2;
		return start;
    }
};

Java:

public class Solution {

    public ListNode mergeKLists(List<ListNode> lists) {
        Queue<ListNode> heap = new PriorityQueue<ListNode>(new Comparator<ListNode>(){
            @Override public int compare(ListNode l1, ListNode l2) {
                return l1.val - l2.val;
            }
        });

        ListNode dummy = new ListNode(0), cur = dummy, tmp;
        for (ListNode list : lists) {
            if (list != null) {
                heap.offer(list);
            }
        }
        while (!heap.isEmpty()) {
            tmp = heap.poll();
            cur.next = tmp;
            cur = cur.next;
            if (tmp.next != null) {
                heap.offer(tmp.next);
            }
        }
        return dummy.next;
    }
}

Python:

class Solution:
    # @param a list of ListNode
    # @return a ListNode
    def mergeKLists(self, lists):
        if len(lists) == 0:
            return None
        if len(lists) == 1:
            return lists[0]

        mid = len(lists) // 2
        left = self.mergeKLists(lists[:mid])
        right = self.mergeKLists(lists[mid:])

        # merge left and right
        dummy = ListNode(0)
        cur = dummy
        while left or right:
            if right == None or (left and left.val <= right.val):
                cur.next = left
                left = left.next
            else:
                cur.next = right
                right = right.next
            cur = cur.next

        return dummy.next
时间: 2024-12-11 18:51:37

[LeetCode] 023. Merge k Sorted Lists (Hard) (C++/Python)的相关文章

Java for LeetCode 023 Merge k Sorted Lists

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. 解题思路一: 之前我们有mergeTwoLists(ListNode l1, ListNode l2)方法,直接调用的话,需要k-1次调用,每次调用都需要产生一个ListNode[],空间开销很大.如果采用分治的思想,对相邻的两个ListNode进行mergeTwoLists,每次将规模减少一半,直到

LeetCode 023 Merge k Sorted Lists

题目要求:Merge k Sorted Lists Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. 分析: 参考网址:http://blog.csdn.net/a83610312/article/details/8554241 思路是:首先将k个链表的第一个节点集合,建堆,然后取出堆顶的节点,链接到结果链表上,然后将该节点的下一个节点入堆,直到所有

[LeetCode 题解]: Merge k Sorted Lists

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. 题意:对k个有序的链表进行归并排序.并分析其复杂度. /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(N

[LeetCode][JavaScript]Merge k Sorted Lists

https://leetcode.com/submissions/detail/28015840/ Merge k Sorted Lists Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. 直接使用了“Merge Two Sorted Lists”里写的方法. http://www.cnblogs.com/Liok3187/p/4514347.ht

[LeetCode] 23. Merge k Sorted Lists 合并k个有序链表

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. 与21. Merge Two Sorted Lists的拓展,这道题要合并k个有序链表,还是可以两两合并. 类似题目: [LeetCode] 21. Merge Two Sorted Lists 合并有序链表 原文地址:https://www.cnblogs.com/lightwindy/p/8512

【leetcode】Merge k Sorted Lists

Merge k Sorted Lists Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. 采用优先队列priority_queue 把ListNode放入优先队列中,弹出最小指后,如果该ListNode有下一个元素,则把下一个元素放入到队列中 1 /** 2 * Definition for singly-linked list. 3 * stru

[LeetCode]23. Merge k Sorted Lists

23. Merge k Sorted Lists Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. 给定k个排序了的链表,合并k个链表成一个排序链表. 本程序思路: 1)首先得到K个链表的长度和存在len中 2)从K个链表中找到值最小的那个节点,把该节点添加到合并链表中 3)重复len次即可把所有节点添加到合并链表中. 注意事项: 1)K个链表中有的

leetCode 23. Merge k Sorted Lists (合并k个排序链表) 解题思路和方法

Merge k Sorted Lists Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. 思路:此题是由合并两个排序链表演化而来,刚开始,想法比较简单,像求最大公共前缀一样,逐一求解:但是最后超时,所以马上意识到出题方是为了使用归并和分治的方法,故重新写了代码. 代码一(超时未过): /** * Definition for singly-link

leetcode 之 Merge k Sorted Lists

Merge k Sorted Lists Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. 思路:把这k个链表放入multiset中,每次从multiset中取出头结点最小的链表,把头结点插入到结果链表中,然后把剩下的非空子链表插入到multiset中 /** * Definition for singly-linked list. * struct