/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(l1==NULL)//判断有一组为空的情况
return l2;
if(l2==NULL)
return l1; if(l1->val>l2->val)//由于我设计的算法问题,需要明确知道第一个值谁小,不妨用l1小,若不满足,就倒一下
return mergeTwoLists(l2,l1);
ListNode* res=l1;//保存头指针,留待返回
while(l2!=NULL)
{
while(l1->next!=NULL && l1->next->val<=l2->val)//直到找出l1下一个比当前l2值大的数,且不能为空
l1=l1->next;
if(l1->next==NULL)//只要额外判断l1下个为空的情况,这个值肯定不会比l2大
{
l1->next=l2;
break;
}
ListNode* l2_next=l2->next;//一定要记住当前l2的下个节点
l2->next=l1->next;//这里一定要画图,特清晰,不画要崩溃
l1->next=l2;//注意这里l1指针停在新加入的节点处
l1=l1->next;
l2=l2_next;//即便l2为空也不要紧啊
} return res;
} ListNode* mergeKLists(vector<ListNode*>& lists) {
int len=lists.size();
if(len==)//提前写好三种情况,都是个数的最小单位了
return NULL;
if(len==)
return lists[];
if(len==)
return mergeTwoLists(lists[],lists[]); vector<ListNode*> list1(len/+);//然后分半,防止有奇数,所以下面是len-len/2-1长度
vector<ListNode*> list2(len-len/-);
int i=;
for(;i<len/+;i++)
list1[i]=lists[i];
for(;i<len;i++)
list2[i-len/-]=lists[i];//划分好后 ListNode* mer1=mergeKLists(list1);//受归并排序的提示,采用递归实现
ListNode* mer2=mergeKLists(list2); return mergeTwoLists(mer1,mer2);
}
};

分析:

结合之前的写好的两个排序的思想,这个几乎没有阻碍就写出来了,但是明显写的慢,对vector没有python的切片这种都不太清晰,明显经验不足。

但是这个题给我提示,还是要画图,分析又快又好,关键是能验证你的想法能不能行。

而且,一个困难的问题,可以拆成多了小题解决,比如这个,分为递归归并策略和两个排序链表连接,特别有效果。

有点小开心的是时间击败了35%,哦对了,这个时间复杂度平均情况我有点不太清楚,但最坏情况是O(max(n)*m*log(m)),n是m个链表的长度。

最新文章

  1. 测试基础:Bug管理那些事_20160910
  2. mongodb系列3 mongo mongoskin 连接以及连接数的问题进阶
  3. jvm 监控
  4. [WP8] ListBox的Item宽度自动填满
  5. ubuntu搭建分布式hadoop-2.6.0概略和错误
  6. LoadCursor 函数
  7. (转载)顺序栈c++实现
  8. C++类中的静态成员变量与静态成员函数
  9. xp下Oracle数据库导入SQLServer数据库数据
  10. 列表(list)之一定义 添加 删除 排序 反转 索引等其他操作
  11. python简明教程代码
  12. ACM ICPC 2017 Warmup Contest 9 I
  13. docker 清理容器的命令
  14. 使用htpasswd实现Nginx验证访问
  15. 20145325张梓靖 《网络对抗技术》 PC平台逆向破解
  16. Codeforces 375C Circling Round Treasures - 最短路 - 射线法 - 位运算
  17. C/C++基础----string, vector, array
  18. ACM ICPC, Damascus University Collegiate Programming Contest(2018) Solution
  19. Ubuntu的常识使用了解
  20. phpstrom设置php环境

热门文章

  1. qt裁剪
  2. python的paramiko模块-远程登录linux主机并操作
  3. P3157 [CQOI2011]动态逆序对(树状数组套线段树)
  4. 应使用sqlplus代替tnsping进行oracle连通性测试
  5. gcc对c++标准的支持
  6. windows安装 php-redis redis 扩展
  7. AnswerOpenCV(1001-1007)一周佳作欣赏
  8. Codeforces Round #425 (Div. 2) Problem C Strange Radiation (Codeforces 832C) - 二分答案 - 数论
  9. 使用vs code搭建C开发环境
  10. luogu1387 最大正方形