[Leetcode] 023. Merge k Sorted Lists (Hard) (C++/java/python)

Source: Internet
Author: User

Index: [Leetcode] leetcode key index (C++/JAVA/PYTHON/SQL)
Github:https://github.com/illuz/leetcode 023. Merge k Sorted Lists (Hard) link :

Title: https://oj.leetcode.com/problems/merge-k-sorted-lists/
Code (GitHub): Https://github.com/illuz/leetcode :

and 021. Merge two Sorted Lists (easy) Similar, this time to merge K. Analysis :

It is clear to think of using the completed Merge two Sorted Lists function.
There are two ways of doing this:
1. (c + +) with the idea of a binary, each list and its adjacent list to Merge, so the scale is reduced by half, and then repeat this, you can O (NKLOGK) completed. For example: [1, 2, ..., N] The first round of the Merge is [1, N/2], [2, n/2+1], ...
2. (Python) is also the idea of a binary, that is, the Lists into two parts, respectively, recursive merge K Sorted Lists into two list, and then the two lists for the Merge two Sorted Lists.

Both of these methods are recursive call, can be memory, with space for time, but I do not know whether hyperspace (Memory Limit exceed), so did not try ~

In addition to the idea of a binary, there is a better way to write, is to use a heap (heap), specifically with the priority queue (Priority queues).
(Java) First put the first node in each List into the precedence queue, each time the maximum node in the queue is fetched, and then the node's next is put in. code :

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 (list s) = = 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
        le FT 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


  


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.