双指针法----->求数组中两数之和

c++版:
class Solution {
private:
    int low=-1;
    int high=-1;
    vector<int>src;
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        low=0;
        high=numbers.size()-1;
        while(low<=high)
        {
            int res=numbers[low]+numbers[high];
            if(res>target)high--;
            else if(res<target)low++;
            else if(res==target)break;
        }
        src.push_back(low+1);
        src.push_back(high+1);
        return src;
    }
};
  
Java版:
class
Solution { private int low=-1; private int high=1; private int[] src; public int[] twoSum(int[] numbers, int target) { low=0; high=numbers.length-1; while(low<=high) { int res=numbers[low]+numbers[high]; if(res>target)high--; else if(res<target)low++; else if(res==target)break; } src=new int[] {low+1,high+1}; return src; } }

猜你喜欢

转载自www.cnblogs.com/z2529827226/p/11747552.html