剑指Offer_编程题 | 和为S的两个数字

参考链接:https://zhuanlan.zhihu.com/p/63235664
在这里插入图片描述

class Solution {
public:
    vector<int> FindNumbersWithSum(vector<int> array,int sum) {
        vector<int> res;
        int first = 0,last = array.size() - 1;
        
        while(first < last)
        {
            if (array[first] + array[last] == sum)	//将等于号的放在前面可以减小时间复杂度
            {
                res.push_back(array[first]);
                res.push_back(array[last]);
                break;
            }
            else if (array[first] + array[last] > sum)
                last --;
            else
               first ++;
        }
        
        return res;
    }
};

在这里插入图片描述

发布了103 篇原创文章 · 获赞 29 · 访问量 4930

猜你喜欢

转载自blog.csdn.net/weixin_43956456/article/details/105695735