[LeetCode][Java] Merge k Sorted Lists

原创 2015年07月10日 11:46:50

题目:

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; }
 * }
 */
 //合并为一个数组,排序,再转化为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] 023. Merge k Sorted Lists (Hard) (C++/Java/Python)

[LeetCode] 023. Merge k Sorted Lists (Hard) (C++/Java/Python)
  • hcbbt
  • hcbbt
  • 2015-03-05 11:19
  • 2354

[LeetCode] 23. Merge k Sorted Lists java

/**23. Merge k Sorted Lists * @param lists * @return 合并k路有序链表 */ public ListNode ...

[Leetcode] Merge k Sorted Lists (Java)

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

LeetCode 23 Merge k Sorted Lists (C,C++,Java,Python)

Problem: Merge k sorted linked lists and return it as one sorted list. Analyze and describe its c...

【LeetCode】23. Merge k Sorted Lists 基于Java的解法

23. Merge k Sorted Lists Total Accepted: 88102 Total Submissions: 372066 Difficulty: Hard Merge k...

【LeetCode-面试算法经典-Java实现】【023-Merge k Sorted Lists(合并k个排好的的单链表)】

【023-Merge k Sorted Lists(合并k个排好的的单链表)】【LeetCode-面试算法经典-Java实现】【所有题目目录索引】原题  Merge k sorted linked l...

leetcode解题之23.Merge k Sorted Lists Java版本(合并k个有序的链表)

leetcode解题之23.Merge k Sorted Lists Java版本(合并k个有序的链表)

[LeetCode]Merge k Sorted Lists

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

leetcode23~Merge k Sorted Lists Add to List

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

【leetcode】23. Merge k Sorted Lists

合并多个已排序的单链表,多种实现方式
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)