LeetCode (力扣) 23. Merge k Sorted Lists (C) - Hard

同步发于 JuzerTech 网站,里面有我软、硬件学习的纪录与科技产品开箱,欢迎进去观看。

这题是 LeetCode 21. Merge Two Sorted Lists 的延伸,把两个链表 ( Linked List ) 增加到多个。

把多个链表 ( Linked List ) 依照大小排序,串接在一起,并回传串接完的 Linked List。

题目与范例如下

You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.

Merge all the linked-lists into one sorted linked-list and return it.


Example 1:

Input: lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]
Explanation: The linked-lists are:
[
1->4->5,
1->3->4,
2->6
]
merging them into one sorted list:
1->1->2->3->4->4->5->6
Example 2:

Input: lists = []
Output: []
Example 3:

Input: lists = [[]]
Output: []

Constraints:

k == lists.length
0 <= k <= 10^4
0 <= lists[i].length <= 500
-10^4 <= lists[i][j] <= 10^4
lists[i] is sorted in ascending order.
The sum of lists[i].length won't exceed 10^4


一开始我的想法是用回圈每次找到最小的依序放入第一个链表 ( Linked List ) 中,但这个方法速度很慢,测试时大约花了312 ms 的时间,后来我改用插入排序法的概念,依序读每个链表 ( Linked List ) 中的值,一个个透过插入排序法插入链表 ( Linked List ) 中对应大小的位置,速度有着明显的提升。

下方为我的代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */

struct ListNode* mergeKLists(struct ListNode** lists, int listsSize) {

	if (listsSize == 0)
		return NULL;
	for (int i = 1; i < listsSize; i++) {
		struct ListNode* ptrnow = lists[0], * ptrpost = lists[0];
		while (lists[i] != NULL) {
			if (ptrnow == NULL) {
				struct ListNode* temp = lists[i];
				lists[i] = lists[i]->next;
				temp->next = ptrnow;
				if (ptrpost != NULL) {
					ptrpost->next = temp;
					ptrpost = ptrpost->next;
				}
				else {
					lists[0] = temp;
					ptrpost = lists[0];
				}
			}
			else if (lists[i]->val < ptrnow->val) {
				struct ListNode* temp = lists[i];
				lists[i] = lists[i]->next;
				temp->next = ptrnow;
				if (ptrnow == lists[0]) {
					lists[0] = temp;
					ptrpost = lists[0];
				}
				else {
					ptrpost->next = temp;
					ptrpost = temp;
				}
			}
			else {
				if (ptrnow != lists[0]) {
					ptrpost = ptrpost->next;
				}
				ptrnow = ptrnow->next;
			}
		}
	}

	return lists[0];
}

下方为时间与空间之消耗

Runtime: 220 ms, faster than 60.37% of C online submissions for Merge k Sorted Lists.

Memory Usage: 8.1 MB, less than 96.50% of C online submissions for Merge k Sorted Lists.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值