42. The two figures and to the S
problem:
An incrementing input and a digital sorted array S, find the two numbers in the array, and so that they are exactly S, and if a plurality of digits equal to S, the product of the output of the minimum number of two.
solve:
thought:
Assumptions: if b> a, and there is,
A + B = S;
(A - m) + (B + m) = S
then: (a - m) (b + m) = ab - (ba) m - m * m <ab; smaller outer described product
that is still about Squeeze method! ! ! Only two pointers
beginning 1.left, right end point
2. If and less than the sum, described too small, left to the right to find a larger number
3. If greater than sum, described too, right left looking for more small number of
4 and equal to the number of left and right return
python code:
# -*- coding:utf-8 -*-
class Solution:
def FindNumbersWithSum(self, array, tsum):
# write code here
result=[]
if not array:
return result
left=0
right=len(array)-1
while(left<right):
csum=array[left]+array[right]
if(csum==tsum):
result.append(array[left])
result.append(array[right])
return result
elif(csum<tsum):
left+=1
else:
right-=1
return result