15算法课程 167. Two Sum II

来源:互联网 发布:网站备案域名查询 编辑:程序博客网 时间:2024/06/05 04:46


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.

You may assume that each input would have exactly one solution and you may not use the same element twice.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2


solution:

可以假设每个输入的目标值都只有一个解决方案,并且不能使用相同的元素相加两次。


code:

class Solution {public:    vector<int> twoSum(vector<int>& numbers, int target) {        vector<int> ans;        int ending = numbers.size() - 1;        int temp;        for(int i = 0; i <= ending; ++i){            int toFound = target - numbers[i];            int temp = search(numbers, i+1, ending, toFound);            if(temp != -1){                ans.push_back(i+1);                ans.push_back(temp+1);                break;            }        }        return ans;    }    int search(vector<int> &n, int low, int high, int target){        while(low <= high){            int mid = (low + high) / 2;            if(n[mid] == target){                return mid;            }            else if(n[mid] > target)                high = mid - 1;            else                low = mid + 1;        }        return -1;    }};