1. 程式人生 > >劍指offer 42. 和為s的兩個數字

劍指offer 42. 和為s的兩個數字

原題

輸入一個遞增排序的陣列和一個數字S,在陣列中查詢兩個數,使得他們的和正好是S,如果有多對數字的和等於S,輸出兩個數的乘積最小的。

輸出描述:

對應每個測試案例,輸出兩個數,小的先輸出。

Reference Answer

思路分析

設定兩個指標,一個指向陣列的起點,一個指向陣列的終點,然後對兩個數字求和,如果和大於目標值,則把後一個指標前移,如果和小於目標值,則把前一個指標後移。兩個指標交匯的時候如果還沒找到,就終止操作。

# -*- coding:utf-8 -*-
class Solution:
    def FindNumbersWithSum
(self, array, tsum): # write code here if len(array) <= 1: return [] left, right = 0, len(array) - 1 temp_res, res = [], [] temp_res = {} while array[left] < array[right]: if array[left] + array[right] < tsum: left +=
1 elif array[left] + array[right] == tsum: index = array[left] * array[right] temp_res[index] = [array[left], array[right]] left += 1 elif array[left] + array[right] > tsum: right -= 1 if not temp_res:
return [] res = sorted(temp_res.items(), key=lambda temp_res:temp_res[0]) return res[0][1]