[Leetcode] merge K sorted lists (merge sort)

Source: Internet
Author: User

Question:

MergeKSorted linked lists and return it as one sorted list. analyze and describe its complexity.

Resolution: merges K ordered linked lists, returns a total ordered linked list, analyzes and describes its complexity. The essence of this question is Merge Sorting, and the average time complexity is O (nlogn ).

Java AC code:

Public class solution {public listnode mergeklists (list <listnode> lists) {If (lists = NULL | lists. size () = 0) {return NULL;} return recursion (lists, 0, lists. size ()-1);} public listnode recursion (list <listnode> lists, int start, int end) {If (start <End) {int center = (start + end) /2; return Merge (recursion (lists, start, center), recursion (lists, center + 1, end);} return lists. get (start);} public listnode Merge (listnode Node1, listnode node2) {listnode result = new listnode (0); listnode head = result; while (node1! = NULL & node2! = NULL) {If (node1.val <node2.val) {result. next = node1; node1 = node1.next;} else {result. next = node2; node2 = node2.next;} result = result. next;} while (node1! = NULL) {result. Next = node1; Result = result. Next; node1 = node1.next;} while (node2! = NULL) {result. Next = node2; Result = result. Next; node2 = node2.next;} return head. Next ;}}


[leetcode] merge K sorted lists (merge sort)

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.