题目描述:

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

本题给我们一个数组和一个目标数要我们返回数组中相加等于目标数的两个元素的下标。

答案(两个元素的下标)必须以数组的形式存放,第一个元素要小于第二个元素。下标不是以0开始计数的。

程序不能使用同一个元素两次。

解题思路:

本题可以先假设两个元素的下标在数组两端,如果相加结果大于target的话令右端减一,小于则左端加一。

 1 class Solution {
 2 public:
 3     vector<int> twoSum(vector<int>& numbers, int target) {
 4         vector<int> result;
 5         int i=0,j=numbers.size()-1;
 6         while(j>i){
 7             if(numbers[i]+numbers[j]==target){
 8                 result.push_back(i+1);
 9                 result.push_back(j+1);
10                 break;
11             }
12             else if(numbers[i]+numbers[j]>target)
13                 j--;
14             else
15                 i++;
16         }
17         return result;
18     }
19 };

 

posted on 2018-02-15 01:53  宵夜在哪  阅读(96)  评论(0编辑  收藏  举报