这道题啊,乍一看很简单,遍历不就完事儿了么,但是其中有一些陷阱,
比如tsum 不存在的情况,比如tsum只存在一个的情况和tsum存在多个需要判断最小乘积的情况
# -*- coding:utf-8 -*-
class Solution:
def FindNumbersWithSum(self, array, tsum):
# write code here
res = []#用来保存对应结果的两个数和他们的乘积,返回的时候只返回res[][:2]
min_mul = float("inf")#初始化的只,因为要成绩最小作比较
for i in range(len(array)):
for j in range(len(array)):
if j > i:#必须要保证array[j]和array[i]不一样,array[j]在后面
if array[i] + array[j] == tsum:
res.append([array[i],array[j],array[i]*array[j]])#保存满足条件的两个值和他们的乘积
if len(res) == 0:#为空则返回None
return None
if len(res) == 1:#只有一组值满足条件则直接返回
return res[0][:2]
else:
for m in range(len(res)):#有多组值得时候返回乘积最小的
if res[m][2] < min_mul:
min_mul = res[m][2]
min_id = m#把乘积最小的id保存下来返回
return res[min_id][:2]
class Solution:
def FindNumbersWithSum(self, array, tsum):
# write code here
res = []#用来保存对应结果的两个数和他们的乘积,返回的时候只返回res[][:2]
min_mul = float("inf")#初始化的只,因为要成绩最小作比较
for i in range(len(array)):
for j in range(len(array)):
if j > i:#必须要保证array[j]和array[i]不一样,array[j]在后面
if array[i] + array[j] == tsum:
res.append([array[i],array[j],array[i]*array[j]])#保存满足条件的两个值和他们的乘积
if len(res) == 0:#为空则返回None
return None
if len(res) == 1:#只有一组值满足条件则直接返回
return res[0][:2]
else:
for m in range(len(res)):#有多组值得时候返回乘积最小的
if res[m][2] < min_mul:
min_mul = res[m][2]
min_id = m#把乘积最小的id保存下来返回
return res[min_id][:2]
or
下面一种更简洁,简洁是主要第一保存两个满足条件的数时候用了辅助数组,去用 if (tsum - i) in array 来判断而避免了遍历
还有就是排序时候直接用了 res.sort(key = lambda x: x[0] * x[1])来排序,
class Solution:
def FindNumbersWithSum(self, array, tsum):
# write code here
res = []
for i in array:
array.remove(i)
if (tsum - i) in array:
res.append([i,(tsum-i)])
if len(res) == 1:
return res[0]
if len(res) == 0:
return None
res.sort(key = lambda x: x[0] * x[1])
return res[0]
def FindNumbersWithSum(self, array, tsum):
# write code here
res = []
for i in array:
array.remove(i)
if (tsum - i) in array:
res.append([i,(tsum-i)])
if len(res) == 1:
return res[0]
if len(res) == 0:
return None
res.sort(key = lambda x: x[0] * x[1])
return res[0]