(java)leetcode-23

Merge k Sorted Lists

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


解题思路:

当时看到这个最开始的想法是两两进行合并然后这样不断循环下去,但是当时想说会不会复杂度有点高就没用了,就用了一种方法说,找到所有队列中的当前节点的最小值,取出添加到原节点的最后,让该节点指向其next,然后不断这样添加直到数组中只有一个非空节点。


/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode mergeKLists(ListNode[] lists)
	{
		ListNode result = new ListNode(0);
		ListNode p = result;
		if(lists.length == 0)
			return null;
		else if(lists.length == 1)
			return lists[0];
		int small1 = -1;
		int n = lists.length;
		for(int i = 0;i<lists.length;i++)
		{
			if(lists[i] == null)
			{
				n--;
				continue;
			}
			if(small1 <0 || lists[i].val < lists[small1].val)
				small1 = i;
		}
		if(small1 <0)
			return null;
		int small2 = findSecondSmallest(lists,small1);
		if(small2 < 0)
			return lists[small1];
		while(n>0)
		{
			p.next = lists[small1];
			lists[small1] = lists[small1].next;
			if(lists[small1] == null)
			{
				small1 = small2;
				small2 = findSecondSmallest(lists,small1);
				n--;
			}
			else if(lists[small1].val > lists[small2].val)
			{
				small1 = small2;
				small2 = findSecondSmallest(lists,small1);
			}
			p = p.next;
			if(n == 1)
			{
				p.next = lists[small1];
				n--;
			}
		}
		return result.next;		
	}
	public int findSecondSmallest(ListNode[] lists,int k)
	{
		int result = -1;
		for(int i = 0;i<lists.length;i++)
		{
			if(i == k || lists[i] == null)
				continue;
			if(result <0 || lists[i].val <lists[result].val)
				result = i;
		}
		return result;
	}
}



结果就LTE了,因为当数组中有大量的短的链表的时候这样是很麻烦的。看了下别人的答案还真是用两两合并的,看来是我想多了...代码就用leetcode里面第三个答案的就好了,写的真的很不错。(My simple java Solution use recursion)。又学到了一种新技能。


public static ListNode mergeKLists(ListNode[] lists){
    return partion(lists,0,lists.length-1);
}

public static ListNode partion(ListNode[] lists,int s,int e){
    if(s==e)  return lists[s];
    if(s<e){
        int q=(s+e)/2;
        ListNode l1=partion(lists,s,q);
        ListNode l2=partion(lists,q+1,e);
        return merge(l1,l2);
    }else
        return null;
}

//This function is from Merge Two Sorted Lists.
public static ListNode merge(ListNode l1,ListNode l2){
    if(l1==null) return l2;
    if(l2==null) return l1;
    if(l1.val<l2.val){
        l1.next=merge(l1.next,l2);
        return l1;
    }else{
        l2.next=merge(l1,l2.next);
        return l2;
    }
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值