您好,登錄后才能下訂單哦!
合并 k 個排序鏈表,返回合并后的排序鏈表。請分析和描述算法的復雜度。
示例:
輸入:
[
1->4->5,
1->3->4,
2->6
]
輸出: 1->1->2->3->4->4->5->6
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/merge-k-sorted-lists
/*
解題思路:
解法一、順序合并
1、lists[0]與lists[1]合并,結果與lists[2]合并...結果與lists[listsSize-1]合并
解法二、分治合并
1、lists[0]與lists[1]合并,lists[2]與lists[3]合并,然后將合并的結果繼續合并。
*/
解法一、順序合并
解法二、分治合并
/*
title: leetcode23. 合并K個排序鏈表
author: xidoublestar
method: 順序合并
type: C
date: 2020-5-27
*/
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
if (!l1)
return l2;
if (!l2)
return l1;
struct ListNode* head = (struct ListNode*)malloc(sizeof(struct ListNode)), * tail = head;
while (l1 && l2) {
if (l1->val < l2->val) {
tail->next = l1;
l1 = l1->next;
}
else {
tail->next = l2;
l2 = l2->next;
}
tail = tail->next;
}
if (l1) tail->next = l1;
else if (l2) tail->next = l2;
tail = head;
head = head->next;
free(tail);
return head;
}
struct ListNode* mergeKLists(struct ListNode** lists, int listsSize) {
if (listsSize == 0)
return NULL;
struct ListNode* res = *lists;
for (int i = 1; i < listsSize; i++)
{
if(lists[i] != NULL)
res = mergeTwoLists(res, lists[i]);
}
return res;
}
/*
title: leetcode23. 合并K個排序鏈表
author: xidoublestar
method: 順序合并
type: C
date: 2020-5-27
*/
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
if ((!l1) || (!l2)) return l1 ? l1 : l2;
struct ListNode head;
head.next = NULL;
struct ListNode* tail = &head;
while (l1 && l2) {
if (l1->val < l2->val) {
tail->next = l1;
l1 = l1->next;
}
else {
tail->next = l2;
l2 = l2->next;
}
tail = tail->next;
}
tail->next = l1 ? l1 : l2;
return head.next;
}
struct ListNode* merge(struct ListNode** lists, int left, int right) {
if (left == right)
return lists[left];
if (left > right)
return NULL;
int mid = (left + right) >> 1;
struct ListNode* p1 = merge(lists, left, mid);
struct ListNode* p2 = merge(lists, mid + 1, right);
return mergeTwoLists(p1, p2);
}
struct ListNode* mergeKLists(struct ListNode** lists, int listsSize) {
if (listsSize == 0)
return NULL;
return merge(lists, 0, listsSize - 1);
}
解法一、順序合并
時間復雜度:O(n*n)
空間復雜度:O(1)
解法二、分治合并
時間復雜度:O(nlogn)
空間復雜度:O(1)
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。