合并 k 個排序鏈表,返回合并后的排序鏈表。請分析和描述算法的復(fù)雜度。
示例:
輸入:
[
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]合并,結(jié)果與lists[2]合并...結(jié)果與lists[listsSize-1]合并
解法二、分治合并
1、lists[0]與lists[1]合并,lists[2]與lists[3]合并,然后將合并的結(jié)果繼續(xù)合并。
*/
解法一、順序合并
解法二、分治合并
/*
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);
}
解法一、順序合并
時間復(fù)雜度:O(n*n)
空間復(fù)雜度:O(1)
解法二、分治合并
時間復(fù)雜度:O(nlogn)
空間復(fù)雜度:O(1)
名稱欄目:leetcode23.合并K個排序鏈表
URL鏈接:http://www.rwnh.cn/article18/jehodp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供面包屑導(dǎo)航、全網(wǎng)營銷推廣、App開發(fā)、Google、網(wǎng)站改版、關(guān)鍵詞優(yōu)化
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)