# 一起刷leetcode(1):Two Sum

https://oj.leetcode.com/problems/two-sum/

1

Two Sum

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.

class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
int n_size = numbers.size();
unordered_map <int, int> numbers_map;
for (int i = 0; i < n_size; i++){
numbers_map[numbers[i]] = i;
}
vector <int > result(2);
for (int i = 0; i < n_size; i++){
int tmp = target - numbers[i];
if (numbers_map.find(tmp) != numbers_map.end()){
if (numbers_map[tmp] != i){
result = i + 1;
result = numbers_map[tmp] + 1;
break;
}
}
}
return result;
}
};


## 收藏七月在线，一起向大牛进阶

ctrl+D或command+D可以快速收藏哦~

• APP下载 七月在线APP
• 微信公众号 扫码免费领课
• 返回顶部