# LeetCode: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

Solution 1:Runtime: 48 ms

class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
vector<int> vec;
for(int i=0;i!=numbers.size()-1;i++)
for(int j=i+1;j!=numbers.size();j++)
if(numbers[i]+numbers[j]==target){
vec.push_back(i+1);
vec.push_back(j+1);
break;
}
return vec;
}
};

Solution 2:Runtime:12ms

class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
map<int, int> table;
map<int, int>::const_iterator iter;
vector<int> result;
for (int i = 0;i!=numbers.size();++i) {
iter = table.find(target - numbers[i]);
if (iter == table.end()) {
table.insert(pair<int, int>(numbers[i], i));
} else {
result.push_back(iter->second + 1);
result.push_back(i + 1);
break;
}
}
return result;
}
};

• 本文已收录于以下专栏：

## Two Sum leetcode c++

• 2015年10月01日 10:47
• 763B
• 下载

leetcode

## 【Leetcode】1. Two Sum

1. Two Sum Total Accepted: 254411Total Submissions: 1031847Difficulty: Easy Given an array...

## DAY1：leetcode #1 Two Sum

1、Two Sum Given an array of integers, return indices of the two numbers such that they add up to a...

## Leetcode-1 Two Sum(Java) -by zzy

Problems: Given an array of integers, find two numbers such that they add up to a specific target n...

## [LeetCode] 2011-03-13 Two Sum

Given an array of integers, find two numbers such that they add up to a specific target number. The...

## leetcode：1. Two Sum（Java实现）

leetcode测试地址：https://leetcode.com/problems/two-sum/#/description 1. Two Sum Given an array o...

## 1-Two Sum @LeetCode

1-Two Sum题目思路题目中得到的信息有： 都是整数，并且可正可负，也可一个值包含多个； 只有一个正确的结果。 方法一：最直接的思路就是两重循环遍历，时间复杂度是O(n^2)，这样肯定不行。方法二...

举报原因： 您举报文章：LeetCode:Two Sum 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)