和为S的两个数字
输入一个递增排序的数组和一个数字S,在数组中查找两个数,使得他们的和正好是S,如果有多对数字的和等于S,输出两个数的乘积最小的。
*/C++
class Solution {
public:
vector<int> FindNumbersWithSum(vector<int> array,int sum) {
vector<int> res;
int i = 0;
int j = array.size()-1;
while(i < j){
if (array[i] + array[j] == sum){
res.push_back(array[i]);
res.push_back(array[j]);
break;
}
else if (array[i]+array[j] > sum)
--j;
else
++i;
}
return res;
}
};
*/python
# -*- coding:utf-8 -*-
class Solution:
def FindNumbersWithSum(self, array, tsum):
# write code here
low,high = 0, len(array)-1
while low < high:
if array[low] + array[high] > tsum:
high -= 1
elif array[low] + array[high] < tsum:
low += 1
else:
return [array[low],array[high]]
return []
# -*- coding:utf-8 -*-
class Solution:
def FindNumbersWithSum(self, array, tsum):
for i in array:
if tsum-i in array:
if tsum-i==i:
if array.count(i)>1:
return [i,i]
else:
return [i,tsum-i]
return []
class Solution:
def FindNumbersWithSum(self, array, tsum):
couple = [tsum-i for i in array]
filtarray = [i for i in array if i in couple]
try:
return [filtarray[0],filtarray[-1]]
except:
return []