题解 | #和为S的两个数字#
和为S的两个数字
http://www.nowcoder.com/practice/390da4f7a00f44bea7c2f3d19491311b
双指针
注意:
1、双指针调整位置
2、更新最小乘积
class Solution { public: vector<int> FindNumbersWithSum(vector<int> array,int sum) { int start =0; int end = array.size()-1; // std::vector< std::pair<int, int> > map_of_eles; std::pair<int, int> res1{0,0}; int tmp_min = INT_MAX; while(start < end){ int tmp = array[start] + array[end]; if(tmp > sum){ end--; } else if(tmp < sum){ start++; } else{ // 相等 if(array[start]*array[end]<tmp_min){ tmp_min = array[start] * array[end]; res1 = {array[start], array[end]}; } start++; end--; } } std::vector<int> res; if(res1.first ==0 && 0== res1.second){ return res; } res.push_back(res1.first); res.push_back(res1.second); return res; } };