合并k个有序的list

题目:已知有k个有序的list, 将这k个list合并成一个有序的lists,注意分析考虑它的效率

思路:k个list都是有序的,这样就可以逐一比较了,设置已经排序好的为move,等待加入的为current,每次都一动move,如果遇到,current介于move和move的下一个节点之间,将已经遍历好的move, 和current当前换位,继续,move被截断的当做新的current,直到遍历结束,有附件,上面有图表示,由于在单位,没有什么编图工具,只能将就将就把

以下是代码实现:实现的过程中,有些问题没有考虑到,所以代码中的注释就是后来补充的,编码水平有限。欢迎大家指正。

 

public ListNode mergeKLists(ArrayList<ListNode> lists) {
		// IMPORTANT: Please reset any member data you declared, as
		// the same Solution instance will be reused for each test case.

		ListNode index = null;
		
		int j = 0;
		if (lists.size() > 0) {  //寻找第一个非空的list最为开头,要不开始元素就是空,例如输入为(),(1),这种情况
			index = lists.get(0);
			while (index == null && j < lists.size()-1) {
				j++;
				index = lists.get(j);
				
			}
		} else {
			return index;
		}

		for (int i = j + 1; i < lists.size(); i++) {

			ListNode current = lists.get(i);
			ListNode move = index;
			boolean whetherhead = true;//条件需要放到这里,因为判断的是每回进入的list的头部大小比较
			//例如 {-5,-2,0,1,1,2 };{ -7,-6,-3 };{ -8,-7,-4,-4,0,2,3,4 };
			while (move != null && current != null) {

				if (current.val >= move.val) {
					if (move.next != null && move.next.val <= current.val) {
						move = move.next;
						continue;

					} else {
						ListNode temp = current;
						current = move.next;
						move.next = temp;
						continue;
					}
				}
				if (current.val < move.val) {
					ListNode temp = move;
					move = current;
					current = temp;
					if (whetherhead) {   //防止开头元素 第一个元素是比较大的,例如(4),(2);没有这个条件,那么输出(2)
						index = move;
						whetherhead = false;
					}
				}
			}

		}

		return index;

	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值