题目:将两个升序链表合并为一个新的升序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
例:
输入:1->2->4, 1->3->4输出:1->1->2->3->4->4
题解:
一、递归法
class Solution:
def mergeTwoLists(self, l1, l2):
if l1 is None:
return l2
elif l2 is None:
return l1
elif l1.val < l2.val:
l1.next = self.mergeTwoLists(l1.next, l2)
return l1
else:
l2.next = self.mergeTwoLists(l1, l2.next)
return l2
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/merge-two-sorted-lists/solution/he-bing-liang-ge-you-xu-lian-biao-by-leetcode-solu/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
知识点:
递归法
第一要素:明确你这个函数想要干什么
第二要素:寻找递归结束条件
第三要素:找出函数的等价关系式->不断缩小参数的范围
本质上,递归就是把一个大问题分解为n个子问题,以原始问题开始,逐级退化到最小的子问题,得到最小子问题的解后,用这些解来回答更高级的子问题,从而最终解答原始问题。
例:斐波那契数列,其中
,对于给定的
,要求
。
第一要素:函数要做的事,就是根据给定的,求得斐波那契数
。
第二要素:递归结束条件就是问题退化到最小的子问题。
第三要素:等价关系式就是。
递归方法适用的两种场景:
1、上述的递归表达式
2、分而治之
链表
一种常见数据结构,单位是节点(Node),节点类成员有Next(当前Node指向的后继Node)和Val(节点值)
节点类
class Node(): #value + next
def __init__ (self, value = None, next = None):
self._value = value
self._next = next
def getValue(self):
return self._value
def getNext(self):
return self._next
def setValue(self,new_value):
self._value = new_value
def setNext(self,new_next):
self._next = new_next
链表类
lass LinkedList():
def __init__(self): #初始化链表为空表
self._head = Node()
self._tail = None
self._length = 0
#检测是否为空
def isEmpty(self):
return self._head == None
#add在链表前端添加元素:O(1)
def add(self,value):
newnode = Node(value,None) #create一个node(为了插进一个链表)
newnode.setNext(self._head)
self._head = newnode
#append在链表尾部添加元素:O(n)
def append(self,value):
newnode = Node(value)
if self.isEmpty():
self._head = newnode #若为空表,将添加的元素设为第一个元素
else:
current = self._head
while current.getNext() != None:
current = current.getNext() #遍历链表
current.setNext(newnode) #此时current为链表最后的元素
#search检索元素是否在链表中
def search(self,value):
current=self._head
foundvalue = False
while current != None and not foundvalue:
if current.getValue() == value:
foundvalue = True
else:
current=current.getNext()
return foundvalue
#index索引元素在链表中的位置
def index(self,value):
current = self._head
count = 0
found = None
while current != None and not found:
count += 1
if current.getValue()==value:
found = True
else:
current=current.getNext()
if found:
return count
else:
raise ValueError ('%s is not in linkedlist'%value)
#remove删除链表中的某项元素
def remove(self,value):
current = self._head
pre = None
while current!=None:
if current.getValue() == value:
if not pre:
self._head = current.getNext()
else:
pre.setNext(current.getNext())
break
else:
pre = current
current = current.getNext()
#insert链表中插入元素
def insert(self,pos,value):
if pos <= 1:
self.add(value)
elif pos > self.size():
self.append(value)
else:
temp = Node(value)
count = 1
pre = None
current = self._head
while count < pos:
count += 1
pre = current
current = current.getNext()
pre.setNext(temp)
temp.setNext(current)
二、迭代法**
class Solution:
def mergeTwoLists(self, l1, l2):
prehead = ListNode(-1)
prev = prehead
while l1 and l2:
if l1.val <= l2.val:
prev.next = l1
l1 = l1.next
else:
prev.next = l2
l2 = l2.next
prev = prev.next
# 合并后 l1 和 l2 最多只有一个还未被合并完,我们直接将链表末尾指向未合并完的链表即可
prev.next = l1 if l1 is not None else l2
return prehead.next
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/merge-two-sorted-lists/solution/he-bing-liang-ge-you-xu-lian-biao-by-leetcode-solu/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
直接依次遍历L1和L2的节点,更易于理解。并且不需要像递归法那样存储中间变量,时间复杂度相同,空间复杂度更优。很直观,没啥可说的。
