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