第六周算法分析与设计Ⅱ:Merge Two Sorted Lists
来源:互联网 发布:linux 杀dhcp进程 编辑:程序博客网 时间:2024/05/29 17:08
问题描述:
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
题目来自于此处
(注:此题难度虽为easy,但感觉挺典型,很有代表性)
解决方案1(非递归):
另起一个结点作为头结点,同时也作为虚拟结点(所谓的dummy node),这样可以方便后续处理的统一。当
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { if(!l1||!l2) return ((l1==l2)?l1:(l1)?l1:l2); //判空的条件。。可能写的有点复杂 ListNode* new_head = new ListNode(1); //不知道还有啥初始化的方法 ListNode* cur_head = new_head; while(l1&&l2){ if(l1->val<=l2->val){ cur_head->next = l1; l1 = l1->next; } else{ cur_head->next = l2; l2 = l2->next; } cur_head = cur_head->next; } cur_head->next = (l1==NULL)?l2:l1; return new_head->next; }
时间复杂度
解决方案2(递归):
递归的方法与非递归的类似,考虑初始条件及递归过程,当
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { if(!l1||!l2) return ((l1==l2)?l1:(l1)?l1:l2); if(l1->val>=l2->val){ l2->next = mergeTwoLists(l1,l2->next); return l2; } else{ l1->next = mergeTwoLists(l1->next,l2); return l1; } }
空间复杂度为
有大神说写了程序不分析复杂度的是瓜皮。。
0 0
- 第六周算法分析与设计Ⅱ:Merge Two Sorted Lists
- (算法分析Week3)Merge Two Sorted Lists[Easy]
- 算法第六周Merge k Sorted Lists[hard]
- LeetCode :: Merge Two Sorted Lists 详细分析
- 算法第五周Merge Two Sorted Lists[easy]
- 算法设计与分析(16)-- Merge k Sorted Lists(难度:hard)
- 算法分析与设计——LeetCode Problem.23 Merge k Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- canvas.drawPath 没起作用
- 在Android M及更高版本中使用 Settings.System 抛出异常"You cannot keep your settings in the secure settings. "
- C++软件工程师笔试题附答案
- Android 生成apk自动重命名名字以及设置签名
- Android 将具体数值转换成dip简单方法
- 第六周算法分析与设计Ⅱ:Merge Two Sorted Lists
- 如何大数据帮助销售人员完成交易?
- jedis和在spring中配置文件
- 欢迎使用CSDN-markdown编辑器
- 微信扫码支付 模式一 (JSAPI)
- 蓝桥杯 基础练习 十六进制转十进制
- npm install 时总是报phantomjs-prebuilt@2.1.14安装失败
- react.js总结学习
- ROS Robotics Projects(1)代码使用编译