leetcode+多路归并排序

匿名 (未验证) 提交于 2019-12-03 00:32:02
点击打开链接
//多路归并 struct ListNode {     int val;     ListNode *next;     ListNode(int x) : val(x), next(NULL) {} };  class Solution { public:     ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {         ListNode* head = new ListNode(0);         ListNode* temp = head;         while(l1 && l2){             if(l1->val < l2->val){                 head->next = l1;                 head = head->next;                 l1 = l1->next;             }             else{                 head->next = l2;                 head = head->next;                 l2 = l2->next;             }         }         if(l1){             head-> next =l1;         }         else{             head->next = l2;         }         return temp->next;     }      ListNode* mergeKLists(vector<ListNode*>& lists) {         int n = lists.size();         if(n==0) return NULL;         while (n>1) {             int k = (n+1) / 2;             for(int i=0; i<n/2; i++){                 lists[i] = mergeTwoLists(lists[i], lists[i+k]);//归并分开看             }             n = k;         }         return lists[0];     } };  

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!