Java for Leetcode 023 Merge K Sorted Lists

Source: Internet
Author: User

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

Problem solving idea One:

Before we had mergetwolists (ListNode L1, ListNode L2) method, the direct call, need k-1 the call, each call needs to produce a listnode[], the space overhead is very large. If the idea of divided treatment, the adjacent two ListNode to mergetwolists, each will reduce the size of half, until the scale becomes 2, the space costs will be much smaller. The Java implementation is as follows:

static public ListNode mergeklists (listnode[] lists) {if (lists.length = = 0) return null;if (lists.length = 1) return lists [0];if (Lists.length = = 2) return mergetwolists (Lists[0], lists[1]);//reference Java for Leetcode 021 Merge, Sorted listselse {L istnode[] halflists = new Listnode[lists.length/2];if (lists.length% 2 = = 0) for (int i = 0; i < halflists.length; i+ +) Halflists[i] = mergetwolists (lists[2 * i], lists[2 * i + 1]); else {for (int i = 0; i < halflists.length; i++) halflist S[i] = mergetwolists (lists[2 * i], lists[2 * i + 1]); Halflists[0] = Mergetwolists (Halflists[0],lists[lists.length-1]);} Return mergeklists (halflists);}}

Two ways to solve problems:

With the priority queue, Java is implemented as follows:

Public ListNode mergeklists (listnode[] lists) {queue<listnode> heap = new Priorityqueue<listnode> (new Comparator<listnode> () {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 (!he Ap.isempty ()) {tmp = Heap.poll (); cur.next = Tmp;cur = Cur.next;if (Tmp.next! = null) Heap.offer (tmp.next);} return dummy.next;}

Java for Leetcode 023 Merge K Sorted Lists

Related Article

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.