"Two Numbers with S" in "Sword Pointing Offer"

Topic description


Input an increasing sorted array and a number S, find two numbers in the array, yes their sum is exactly S, if the sum of multiple pairs of numbers is equal to S, output the smallest product of the two numbers.

Code


//利用了等差数列,两边之积必定小于中间之积。
//若两数之和大于sum,则末尾数向左移动一个。小于则右移。
class Solution {
public:
    vector<int> FindNumbersWithSum(vector<int> array,int sum) {
        vector<int> res;
        int size = array.size();

        int i =0;
        int j = size - 1;
        while(i < j){
            if(array[i] + array[j] == sum){
                res.push_back(array[i]);
                res.push_back(array[j]);
                break;
            }
            while(  array[i] + array[j] > sum){
                j--;
            }
            while( array[i] + array[j] < sum){
                i++;
            }          
        }
        return res;
    }
};

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325609420&siteId=291194637