題目描述:
輸入一個遞增排序的數組和一個數字S,在數組中查找兩個數,使得他們的和正好是S,如果有多對數字的和等於S,輸出兩個數的乘積最小的。
思路:
雙指針
代碼
# -*- coding:utf-8 -*-
class Solution:
def FindNumbersWithSum(self, array, tsum):
# write code here
if not array or array==[]:
return []
p1,p2=0,array.index(array[-1])
res=dict()
while p2-p1>=1:#終止的條件是兩個指針相鄰
while p2-p1>=1 and array[p1]+array[p2]<tsum:#如果兩數之和小於給定的和
p1+=1#前面的指針向後走
while p2-p1>=1 and array[p1]+array[p2]>tsum:
p2-=1#如果當前兩數之和大於給定的和,後面的指針向後走
while p2-p1>=1 and array[p1]+array[p2]==tsum:
res[str(array[p1]*array[p2])]=[array[p1],array[p2]]#若果相等的話,就存入字典,並且前面的指針往後走
p1+=1
return [] if not res else res[sorted(res,cmp=lambda x,y:int(x)-int(y))[0]]