LeetCode——合并K个排序链表
题目地址:https://leetcode-cn.com/problems/merge-k-sorted-lists/
解题思路:简单的分治算法
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { private: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { ListNode *Head=new ListNode(0); ListNode *p,*q,*h; p=l1; q=l2; h=Head; while(p&&q){ if(p->val>=q->val){ h->next=q; h=h->next; q=q->next; } else{ h->next=p; h=h->next; p=p->next; } } if(p) h->next=p; else h->next=q; return Head->next; } ListNode *merge(vector<ListNode*>& lists,int l,int r){ if (l == r) return lists[l]; if (l > r) return nullptr; int mid = (l + r) >> 1; return mergeTwoLists(merge(lists, l, mid), merge(lists, mid + 1, r)); } public: ListNode* mergeKLists(vector<ListNode*>& lists) { return merge(lists,0,lists.size()-1); } };
相关推荐
dbhllnr 2020-06-04
koushr 2020-11-12
范范 2020-10-28
zhaochen00 2020-10-13
Mars的自语 2020-09-27
steeven 2020-09-18
kka 2020-09-14
qiangde 2020-09-13
聚沙成塔积水成渊 2020-08-16
aanndd 2020-08-12
范范 2020-07-30
bluetears 2020-07-28
mingyunxiaohai 2020-07-19
horizonheart 2020-07-19
liushall 2020-07-18
bluetears 2020-07-05
fengshantao 2020-07-02
liuweixiao0 2020-06-27