【LeetCode 21】Merge Two Sorted Lists(Python)
来源:互联网 发布:买电影票的软件 编辑:程序博客网 时间:2024/04/29 20:06
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.
题目分析:给定两个有序链表,将他们合并为一个有序链表。
方法一:
1.思路:
- L1,L2都不为空时,进行以下步骤
- 双重循环L1,L2。
- 用L1的第一个元素与整个L2比较找到零界值。
- 将零界值之前的元素都插入L(新创建的列表)然后插入L1[0]
- 取L2[1]与L2剩下的元素比较找出临界值。
- 。。。 。。。
- L1和L2要删掉每次用过的
- 当L1,L2都为空时,返回L
2.缺点:双重循环导致时间复杂度过大O(n²) 优点:不用数据结构的知识也可以做
3.代码:(运行出错)
class Solution: def mergeTwoLists(self, l1, l2): if not l1: #为空的时候是0,否则是1 return l2 elif not l2: return l1 else: l=[] for i in range(len(l1)): for j in range(len(l2)): if i<=j: for m in range(j): l.extend(l2[m]) l.extend(l1[i]) else: l.extend(l1[i])d=Solution()l1=[1,3]l2=[2,4]c=d.mergeTwoLists(l1,l2)print(c)
4.总结:思路没错,但是运行的时候提示extend那里出错了,暂时没搞懂怎么去修改。
方法二:(成功提交)
1.思路:数据结构中链表,每个节点包括两部分(数据域,指向下一节点的指针)。然后运用递归当达到一方为空,或都为空时停止。
2.代码:
class Solution: def mergeTwoLists(self, l1, l2): if not l1: return l2 elif not l2: return l1 else: if l1.val<=l2.val: l1.next=self.mergeTwoLists(l1.next,l2) return l1 else: l2.next=self.mergeTwoLists(l1,l2.next) return l2
3.总结:代码少,简单。需要能够很好的了解数据结构。这是参考网上别人的思路写的。
阅读全文
1 0
- 【LeetCode 21】Merge Two Sorted Lists(Python)
- 【LeetCode with Python】 Merge Two Sorted Lists
- [leetcode:python]21.Merge Two Sorted Lists
- Leetcode-Merge Two Sorted Lists-Python
- 【Leetcode】【python】Merge Two Sorted Lists
- LeetCode 21 Merge Two Sorted Lists (C,C++,Java,Python)
- LeetCode(21)Merge Two Sorted Lists
- [LeetCode 21] Merge Two Sorted Lists Solution
- [leetcode 21] Merge Two Sorted Lists
- LeetCode 21:Merge Two Sorted Lists
- LeetCode | #21 Merge Two Sorted Lists
- [Leetcode] 21 - Merge Two Sorted Lists
- leetcode.21------------Merge Two Sorted Lists
- [leetcode]21 Merge Two Sorted Lists
- Leetcode NO.21 Merge Two Sorted Lists
- leetcode[21 链表]Merge Two Sorted Lists
- leetcode-21 Merge Two Sorted Lists
- leetCode #21 Merge Two Sorted Lists
- Codeforces864D(构造水题?)
- 更新安全补丁后无法读取查询导入Excel问题解决说明书
- CSS实现垂直居中和水平居中
- 从Cassandra到分布式存储系统-目录
- 章节8 支持的操作系统
- 【LeetCode 21】Merge Two Sorted Lists(Python)
- Java内部类的定义及在外部使用的方法
- 34岁!100天!学会Java编程(Day16-Day19)—MySQL与JDBC编程
- 合唱团
- Python爬虫知识点二
- 章节9 性能和资源使用
- CentOS安装Chrome及Please start Google Chrome as a normal user. To run as root, you must specify an ...
- AUC理解与实现
- Top 10 Machine Learning Algorithms for Beginners