JZ42 和为S的两个数字

思路

假设:若b>a,且存在,
a + b = s;
(a - m ) + (b + m) = s
则:(a - m )(b + m)=ab - (b-a)m - m*m < ab;说明外层的乘积更小
也就是说依然是左右夹逼法!!!只需要2个指针
1.left开头,right指向结尾
2.如果和小于sum,说明太小了,left右移寻找更大的数
3.如果和大于sum,说明太大了,right左移寻找更小的数
4.和相等,把left和right的数返回

代码:

class Solution {
public:
    # define NULL __null
    vector<int> FindNumbersWithSum(vector<int> array,int sum) {
        int low = 0,high = array.size()-1;
        vector<int>result;
        while(low<high)
        {
            while(array[low]+array[high]>sum)
            {
                high = high-1;
            }
            while(array[low]+array[high]<sum)
            {
                low = low + 1;
            }
            if(array[low]+array[high]==sum)
            {
                result.push_back(array[low]);
                result.push_back(array[high]);
                break;
            }
        }
        return result;
    }
};

 

posted @ 2021-09-26 16:24  A-inspire  Views(28)  Comments(0Edit  收藏  举报