[leetcode-167-Two Sum II

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

思路:

刚开始打算用map记录数值与下标。用map的count查找target。发现map不能处理数组中有重复数据情况,而且费空间。

参考别人的方法,使用两个指针,从高和低处来判断。

vector<int> twoSum(vector<int>& numbers, int target)
     {
         vector<int>ret;
        // unordered_map<int,int>mp;//map hash方法不行 不能处理重复数据情况
         int low = 0, high = numbers.size() - 1;
         while (low < high)
         {
             if (numbers[low]+numbers[high] == target)
             {
                 ret.push_back(low+1);
                 ret.push_back(high+1);
                 break;
             }
             else if (numbers[low] + numbers[high] < target)
             {
                 low++;
             }
             else high--;
         }
         return ret;
     }

参考:

https://discuss.leetcode.com/topic/12660/a-simple-o-n-solution