标签: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()排序。
将排序后的数组重新转化为链表,返回链表的头结点。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ //合并为一个数组,排序,再转化为ListNode public 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
标签:leetcode java merge k sorted lists
原文地址:http://blog.csdn.net/evan123mg/article/details/46828789