# 1. Two Sum

## 1. Two Sum

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

Analysis:

Source Code（C++）:

#include <iostream>
#include <vector>
#include <map>
using namespace std;

class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int, int> m;
vector<int> res;
map<int, int>::iterator it;
for(int i=0; i<nums.size(); i++) {
it = m.find(target-nums.at(i));
if (it != m.end()){
res.push_back(it->second);
res.push_back(i);
return res;
}
m[nums.at(i)]=i;
}
return res;//不加此句在leetcode上会出编译错误
}
};

int main() {
Solution sol;
vector<int> res;
vector<int> nums;
nums.push_back(2);
nums.push_back(7);
nums.push_back(2);
nums.push_back(15);
res = sol.twoSum(nums, 4);
for (int i=0; i<res.size(); i++){
cout << res.at(i);
}
return 0;
}

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

## #1 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

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

## 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：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 1.Two Sum 解题报告

LeetCode 1. Two Sum 解题报告

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