題目思路及代碼如下:
# -*- coding:utf-8 -*-
class Solution:
def FindNumbersWithSum(self, array, tsum):
# write code here
# 使用左右兩個指針來遍歷整個數(shù)組挣棕。左指針從數(shù)組頭部開始坷牛,右指針從數(shù)組尾部開始蕴侣,若兩數(shù)和等于tsum雁歌,則返回兩個數(shù);
# 若兩數(shù)和大于tsum,則右指針向左移一位活合;若兩數(shù)和小于tsum,則左指針右移一位
sumS = []
leftPtr = 0
rightPtr = len(array) - 1
while leftPtr <= rightPtr:
if array[leftPtr] + array[rightPtr] == tsum:
sumTemp = []
sumTemp.append(array[leftPtr])
sumTemp.append(array[rightPtr])
sumS.append(sumTemp)
# 這里要注意雏婶,由于不是只輸出一組和為S的數(shù)字就可以了,而是需要進一步比較乘積白指,因此這里還需要繼續(xù)遍歷留晚,直到遍歷完所有的組合
leftPtr += 1
elif array[leftPtr] + array[rightPtr] > tsum:
rightPtr -= 1
else:
leftPtr += 1
# sumS中保存了所有和為tsum的兩個數(shù),以[[],[],[]...]的形式保存
# 下面需要判斷計算每兩個數(shù)的乘積告嘲,返回乘積最小的兩個數(shù)
if len(sumS) == 0:
return []
elif len(sumS) > 1:
multiply = []
for sumSS in sumS:
multiplyTemp = sumSS[0] * sumSS[1]
multiply.append(multiplyTemp)
sumMin = multiply[0]
indexMin = 0
for index in range(1, len(multiply) - 1):
if multiply[index] < sumMin:
sumMin = multiply[index]
indexMin = index
return sumS[indexMin]
elif len(sumS) == 1:
return sumS[0] #對于輸出部分需要注意错维,雖然說要輸出兩個數(shù),但是這兩個數(shù)作為一個list整體輸出也是可以的
if __name__ == "__main__":
s = Solution()
array = [1, 2, 4, 7, 11, 15]
tsum = 15
a, b = s.FindNumbersWithSum(array, tsum)
print(a, b)