66、加一
class Solution(object):
def plusOne(self, digits):
"""
对用列表表示的数字进行加一操作
Args:
digits (List[int]): 表示数字的整数列表,每个元素是0-9的数字,例如[1,2,3]表示数字123
Returns:
List[int]: 加一后的结果列表,例如输入[1,2,3]返回[1,2,4]
:type digits: List[int]
:rtype: List[int]
"""
digits_str=''.join(map(str,digits))
plusone=int(digits_str)+1
return list(map(int, str(plusone)))
时间复杂度分析O(n)
map(str, digits)
:遍历列表将每个元素转为字符串,时间复杂度为 O(n)
join()
:拼接字符串需要遍历所有字符,时间复杂度为 O(n)
int(digits_str)
:字符串转整数的过程需要扫描每一位,时间复杂度为 O(n)
+1
操作:整数加法在极端情况(如全9数字)需要处理所有位,时间复杂度为 O(n)
str(plusone)
和结果列表转换:最终转换回列表需要处理所有结果位,时间复杂度为 O(n)
空间复杂度分析O(n)
中间生成的字符串digits_str
占用 O(n) 空间
转换后的整数plusone
在内存中存储需要 O(n) 位空间
最终返回的结果列表占用 O(n) 空间
关键结论
该算法通过类型转换实现功能,时间和空间复杂度均为线性阶。虽然实现简洁,但存在以下潜在问题:
1.当输入列表长度超过 10^18 时可能触发Python大整数计算的性能下降
2. 数字转字符串操作无法处理前导零的特殊需求(需看具体业务场景)
3. 空间占用是输入规模的两倍(原始列表+中间字符串+结果列表)
67、二进制求和
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
a_lst_rev=list(map(int,a))
a_lst_rev.reverse()
b_lst_rev=list(map(int,b))
b_lst_rev.reverse()
a_otc=0
for i in range(len(a_lst_rev)):
a_otc+=a_lst_rev[i]*2**i
b_otc=0
for i in range(len(b_lst_rev)):
b_otc+=b_lst_rev[i]*2**i
s=a_otc+b_otc
re=bin(s)[2:]
return re
def addBinary(self, a, b):
"""
将两个二进制字符串相加并返回二进制结果
Args:
a (str): 二进制字符串形式的第一个加数,如'1010'
b (str): 二进制字符串形式的第二个加数,如'1101'
Returns:
str: 二进制字符串形式的和,如'10111'
"""
a_int = int(a,2)
b_int = int(b,2)
sum = a_int + b_int
sum_bin = bin(sum)[2:]
return sum_bin