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

（如果是有序数组，可以用双指针来做，参见Two Sum II - Input array is sorted

map:

Internally, the elements in a map are always sorted by its key following a specific strict weak ordering criterion indicated by its internal comparison object (of type Compare).

map containers are generally slower than unordered_map containers to access individual elements by their key, but they allow the direct iteration on subsets based on their order.

map::operator[]:

Logarithmic in size.

unordered_map:

Internally, the elements in the unordered_map are not sorted in any particular order with respect to either their key or mapped values, but organized into buckets depending on their hash values to allow for fast access to individual elements directly by their key values (with a constant average time complexity on average).

unordered_map containers are faster than map containers to access individual elements by their key, although they are generally less efficient for range iteration through a subset of their elements.

unordered_map::operator[]:

Average case: constant.
Worst case: linear in container size.

ps: 严格来说，target-numbers[i]可能溢出int，因此提升为long long int更鲁棒。

class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
vector<int> ret(2,-1);
unordered_map<int, int> m;    //value->index map
for(int i = 0; i < numbers.size(); i ++)
{
if(m.find(target-numbers[i]) == m.end())
//target-numbers[i] not appeared
m[numbers[i]] = i;
else
{
ret[0] = m[target-numbers[i]]+1;
ret[1] = i+1;
return ret;
}
}
}
};

#### Leetcode 第 1 题(Two Sum)

2016-04-03 13:58:58

#### LeetCode第一题（c++）

2016-11-03 21:37:01

#### leetcode小白解题记录——第一题

2016-08-12 10:19:00

#### LeetCoder第一题

2015-04-14 10:51:03

#### 【LeetCode】LeetCode——第1题：Two Sum

2016-01-04 17:01:58

#### 【LeetCode】LeetCode——第11题：Container With Most Water

2016-04-22 19:57:57

#### 【 LeetCode】 |Two Sum

2018-02-26 17:14:59

#### leetcode部分题目（C++）

2016-07-30 23:01:36

#### leetcode第11题

2015-07-24 15:13:05

#### leetcode java解答答案

2015年12月20日 36KB 下载

leetcode第一题