# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
l3 = ListNode(0)
p3 = l3
tmpsum = 0
while True:
if l1:
tmpsum += l1.val
l1 = l1.next
if l2:
tmpsum += l2.val
l2 = l2.next
p3.val = tmpsum%10
tmpsum = tmpsum//10
if l1 == None and l2 == None and tmpsum == 0:
break
p3.next = ListNode(0)
p3 = p3.next
return l3
主要思想和计算加法的思想一样,先看l1是否有数字,有就加,再看l2,直到l1,l2和进位都为空的时候就停止循环。往新链表里插入节点时,要先初始化一个ListNode,再插入。
这种有序矩阵,首先想到的是从右上角判断,先判断是否大于最后一个数,如果不大于就搜索本行,再没有就返回false。需要注意列表中没有数的情况。如[[]],[[1]]这种情况。
class Solution:
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
l1 = len(matrix)
if l1 == 0:
return False
l2 = len(matrix[0])
if l2 == 0:
return False
for i in range(l1):