本题来自《剑指offer》 和为S的两个数字
题目:
输入一个递增排序的数组和一个数字S,在数组中查找两个数,使得他们的和正好是S,如果有多对数字的和等于S,输出两个数的乘积最小的。
思路:
头尾双向夹逼遍历,题目是递增排序的数组,当和大于当前值是,那么就向前遍历,如果小于那么就向后遍历。
要求是乘积最小,理论讲,两数相距最远,其乘积最小。
Python Code:
# -*- coding:utf-8 -*-
class Solution:
def FindNumbersWithSum(self, array, tsum):
# write code here
result = [] #result cache,empty
if not isinstance(array, list): #boundart condition judgement
return result
behind = 0 #first index of array
ahead = len(array)-1 #last index of array
while behind<ahead: #the condition is behind small ahead
cursum = array[behind]+array[ahead] #summation
if cursum==tsum: #if cursum equal target
result.append(array[behind]) #then,append the value
result.append(array[ahead])
break
elif cursum>tsum: #if cursum large target
ahead -= 1 #then,previous
else:
behind += 1 #if cursum small target,then later
return result
来源:https://www.cnblogs.com/missidiot/p/10783745.html