题目
2,3,4数之和
非leetcode,自己酌情修改亲测可过
思路
双指针加循环
代码
def twosum(num,target): #dict
dict = {}
for i,nums in enumerate(num):
if nums in dict:
return [dict[nums],i]
else:
dict[target - nums]=i
a = twosum([1,2,4,6,7,9],13)
print(a)
def twosum(num,target): #twopoints
i = 0
j = len(num)-1
list = []
while i<j:
if num[i]+num[j]<target:
i += 1
elif num[i]+num[j]>target:
j-=1
elif num[i]+num[j]==target:
list.append([i,j])
i +=1
j -=1
return list
a = twosum([1,2,4,6,7,9],13)
print(a)
def three_sum(num,target):
list1 = []
for k in range(len(num)-1):
i = k+1
j = len(num) - 1
while i<j:
if num[i] + num[j]+num[k] < target:
i += 1
elif num[i]+num[j]+num[k]>target:
j-=1
elif num[i]+num[j]+num[k]==target:
list1.append([k,i,j])
i +=1
j -=1
return list
a = three_sum([1,2,4,6,7,9],14)
print(a)
def four_sum(num,target):
num.sort()
list1 = []
for k in range(len(num)-1):
for p in range(k+1,len(num)-1):
i = p+1
j = len(num)-1
while i<j:
if num[i] + num[j] + num[k] + num[p] < target:
i += 1
elif num[i]+num[j]+num[k]+num[p]>target:
j-=1
elif num[i]+num[j]+num[k]+num[p]==target:
list1.append([k,p,i,j])
i +=1
j -=1
return list1
a = four_sum([1,2,4,6,7,9],14)
print(a)