学会思考
刻意练习
/* Two Sum
 *Description:
Given an array of integers that is already sorted in ascending order,
find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that
they add up to the target, where index1 must be less than index2.
Please note that your returned answers (both index1 and index2) are not zero-based.
*/

class Solution{
public:
    vector<int> twoSum(vector<int>& numbers, int target){
        vector<int> result;
        int low = 0,high = numbers.size()-1;
        while (low < high) {
            if(numbers[low]+numbers[high] == target){
                result.push_back(low+1);
                result.push_back(high+1);
                return result;
            }
            else
            {
                numbers[low]+numbers[high] > target ? high--:low++;
            }
        }
        return result;
    }
};

  

posted on 2020-03-06 17:29  Worty  阅读(80)  评论(0编辑  收藏  举报