[劍指offer] 42. 和為S的兩個數字
阿新 • • 發佈:2018-12-21
題目描述
輸入一個遞增排序的陣列和一個數字S,在陣列中查詢兩個數,使得他們的和正好是S,如果有多對數字的和等於S,輸出兩個數的乘積最小的。輸出描述:
對應每個測試案例,輸出兩個數,小的先輸出。
思路:
左右指標夾逼
class Solution { public: vector<int> FindNumbersWithSum(vector<int> arr, int sum) { vector<int> res; int pl = 0; int pr = arr.size() - 1; while (pl < pr) { if (arr[pl] + arr[pr] > sum) pr--; if (arr[pl] + arr[pr] == sum) { res.push_back(arr[pl]); res.push_back(arr[pr]); break; } if (arr[pl] + arr[pr] < sum) pl++; } return res; } };