標籤:leetcode java merge k sorted lists
題目:
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
題意:
合并 K 個有序的鏈表,把他們合并成為一個有序鏈表。分析並描述它的複雜度。
演算法分析:
先將k個鏈錶轉化為數組,合并,之後利用Collections.sort()排序。
將排序後的數組重新轉化為鏈表,返回鏈表的頭結點。
AC代碼:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ //合并為一個數組,排序,再轉化為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; } }}
著作權聲明:本文為博主原創文章,轉載註明出處
[LeetCode][Java] Merge k Sorted Lists