[Leetcode] [Java] Merge k Sorted Lists

Source: Internet
Author: User

Title:

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

Test Instructions:

Merge the K-ordered lists and merge them into an ordered list. Analyze and describe its complexity.

Algorithm Analysis:

The K-linked list is converted to an array, merged, and then sorted by Collections.sort ().

Converts the sorted array back into a linked list, returning the head node of the linked list.

AC Code:

/** * Definition for singly-linked list. * public class ListNode {* int val; * List Node Next; * ListNode (int x) {val = x;}} */////////////merge into an array, sort, and then convert to Listnodepublic class solution {public ListNode mergeklists (        Listnode[] lists) {arraylist<integer> alist= new arraylist<integer> ();        ListNode Res=null;                ListNode newhead =new ListNode (-1); if (lists==null| |            lists.length==0) return res;         for (int i=0;i<lists.length;i++) {ListNode temlist=lists[i];         while (Temlist!=null) {alist.add (temlist.val);         Temlist=temlist.next;     }} collections.sort (Alist);     if (Alist.size () ==0) return res;     else {res=new ListNode (alist.get (0));     Newhead.next=res;     for (int i=0;i<alist.size () -1;i++) {res.next=new ListNode (Alist.get (i+1));     Res=res.next;     } return newhead.next; }    }}


Copyright NOTICE: This article is the original article of Bo Master, reprint annotated source

[Leetcode] [Java] Merge k Sorted Lists

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.