【给出一个整型数组 numbers 和一个目标值 target,请在数组中找出两个加起来等于目标值的数的下标,返回的下标按升序排列。】
class Solution:
def twoSum(self , numbers: List[int], target: int) -> List[int]:
# write code here
hashmap = {}
for index, num in enumerate(numbers):
another_num = target - num
if another_num in hashmap:
return [hashmap[another_num]+1, index+1]
hashmap[num] = index
return None
【给出一个有n个元素的数组S,S中是否有元素a,b,c满足a+b+c=0?找出数组S中所有满足条件的三元组。】
class Solution:
def threeSum(self , num: List[int]) -> List[List[int]]:
# write code here
num.sort()
res = []
for k in range(len(num)-2):
if num[k] > 0:break
if k > 0 and num[k] == num[k - 1]: continue
i,j = k+1,len(num)-1
while i<j:
s = num[i] + num[j] + num[k]
if s<0:
i += 1
while i<j and num[i]==num[i-1]:i+=1
elif s>0:
j -= 1
while i<j and num[j]==num[j+1]:j-=1
else:
res.append([num[k],num[i],num[j]])
i += 1
j -= 1
while i<j and num[i]==num[i-1]:i+=1
while i<j and num[j]==num[j+1]:j-=1
return res