Array - 数组问题


1. Two Sum

已知数组 nums,求其中两数之和等于 target 的下标。

1
2
3
4
5
6
7
8
9
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
all = dict()
for x, y in enumerate(nums):
if all.get(target - y, None) != None:
# if target - y in all: # 使用 in 简化逻辑
return [all[target-y], x]
else:
all[y] = x

67. Add Binary

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution:
def addBinary(self, a: str, b: str) -> str:
length = max(len(a), len(b)) + 1
a = '0' * (length - len(a)) + a
b = '0' * (length - len(b)) + b
ret = ''
c = 0
for i in range(length):
s = int(a[-i-1]) + int(b[-i-1]) + c
ret = str(s % 2) + ret
c = s // 2
if ret[0] == '0':
return ret[1:]
else:
return ret
作者

Cheng

发布于

2020-01-08

更新于

2022-08-06

许可协议

评论