[剑指offer] 42. 和为S的两个数字

题目描述

输入一个递增排序的数组和一个数字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;
    }
};

猜你喜欢

转载自www.cnblogs.com/ruoh3kou/p/10154958.html