Two Sum (Medium)

Description

Given an array of integers, 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.

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

Analysis

方法有很多。我用的是直接排序之后,用头尾指针开始扫。找到就退出

My Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
//C++
class Solution {
vector<int>ans;
public:
vector<int> twoSum(vector<int> &numbers, int target) {

vector<int>numcpy(numbers);
sort(numbers.begin(),numbers.end());
int len = numbers.size();
int l = 0, r = len-1;
while(l<r){
if(numbers[l]>target-numbers[r])
r--;
else if(numbers[l]<target-numbers[r])
l++;
else
break;
}
if(l<r){
for(int i = 0;i<len;i++){
if(numcpy[i]==numbers[l]||numcpy[i]==numbers[r])
ans.push_back(i+1);
}
}
return ans;
}
};