classSolution: deftwoSum(self, nums: List[int], target: int) -> List[int]: all = dict() for x, y inenumerate(nums): ifall.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
classSolution: defaddBinary(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 inrange(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