剑指offer 57:和为s的两个数字

在这里插入图片描述
思路
定义首指针和尾指针向中间遍历即可

class Solution {
    
    
public:
    vector<int> twoSum(vector<int>& nums, int target) {
    
    
        int p1=0;
        int p2=nums.size()-1;
        while(p1!=p2) {
    
    
            if(nums[p1]+nums[p2]==target) return vector<int> {
    
    nums[p1],nums[p2]};
            else if(nums[p1] + nums[p2] > target) p2--;
            else p1++; 
        }
        return {
    
    0,0};
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_44537258/article/details/114030383