Merge k Sorted Lists

11 篇文章 0 订阅

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

Example:

Input:
[
  1->4->5,
  1->3->4,
  2->6
]
Output: 1->1->2->3->4->4->5->6

大概意思:将数组中的链表进行排序
public static void sort(ListNode[] lists, int low, int high) {
		int start = low;
		int end = high;
		ListNode key = lists[low];

		while (end > start) {
			while (end > start && lists[end].val >= key.val)
				end--;
			if (lists[end].val <= key.val) {
				ListNode temp = lists[end];
				lists[end] = lists[start];
				lists[start] = temp;
			}
			while (end > start && lists[start].val <= key.val)
				start++;
			if (lists[start].val >= key.val) {
				ListNode temp = lists[start];
				lists[start] = lists[end];
				lists[end] = temp;
			}
		}
		if (start > low)
			sort(lists, low, start - 1);
		if (end < high)
			sort(lists, end + 1, high);
	}

	public static ListNode mergeKLists(ListNode[] lists) {

		List<ListNode> Alist = new ArrayList<ListNode>();
		for(ListNode ln : lists) {
			if(ln != null) {
				Alist.add(ln);
			}
		}
		
		if(Alist.size() == 0)
			return null;
		
		lists = Alist.toArray(new ListNode[Alist.size()]);
		sort(lists, 0, lists.length - 1);
		ListNode node = new ListNode(lists[0].val);
		ListNode head = node;
		for (int t = 0;;) {

			if (t == lists.length - 1) {
				node.next = lists[t].next;
				return head;
			} else if (lists[t].next == null) {
				t++;
				node.next = new ListNode(lists[t].val);
				node = node.next;
				continue;
			}

			for (int i = t + 1;; i++) {
				ListNode temp = lists[t].next;
				if (lists[i].val >= temp.val) {
					int j = t;
					while (j < i - 1) {
						lists[j] = lists[++j];
					}
					lists[j] = temp;
					break;
				} else if(i == lists.length - 1) {
					int j = t;
					while (j < i) {
						lists[j] = lists[++j];
					}
					lists[j] = temp;
					break;
				}
			} 
			node.next = new ListNode(lists[t].val);
			node = node.next;
		}
	}
看了一下别人的实现,没有我觉得特别好的,自己大概的思路是1.排序成一个数组 2.取出一个,利用插入排序将取出的那个链表下一次进行排序
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

李文区

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值