Two numbers to prove safety office- and S - the cattle off network

Title: Enter a sorted array and incrementing a number S, find the two numbers in the array, and so that they are exactly S, and if a plurality of digits equal to S, the product of the output of the minimum number of two. Corresponding to each test case, the output of two numbers, the first small output.
Thinking: Select two numbers from both sides of the array, respectively, subscripts l and r. When greater than sum, -r, and when less than the sum, ++ l. When first encountered the same situation, the output can be. The product of these two numbers satisfying the condition of the product must be minimal. Because: simultaneous circumferential length (and), area of the square (the product) is larger than a rectangle, and a rectangle side length of the larger gap, the smaller the area.

class Solution {
public:
    vector<int> FindNumbersWithSum(vector<int> array,int sum) {
        int l = 0,r=array.size()-1;
        vector<int> ans;
        while(l<r)
        {
            if(array[l]+array[r]==sum)
            {
                ans.push_back(array[l]);
                ans.push_back(array[r]);
                return ans;
            }
            if(array[l]+array[r]>sum)
                --r;
            else
                ++l;
        }
        return {};
    }
};

Guess you like

Origin blog.csdn.net/qq_43387999/article/details/91348711