-
Notifications
You must be signed in to change notification settings - Fork 0
/
056. 两数之和.cpp
37 lines (37 loc) · 1.07 KB
/
056. 两数之和.cpp
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
28
29
30
31
32
33
34
35
36
37
class Solution {
public:
/*
* @param numbers: An array of Integer
* @param target: target = numbers[index1] + numbers[index2]
* @return: [index1 + 1, index2 + 1] (index1 < index2)
*/
vector<int> twoSum(vector<int> &numbers, int target) {
// write your code here
vector<int> res;
map<int, int> data;
for(int i=0; i<numbers.size(); i++)
data.insert(map<int, int>::value_type(numbers[i], i));
for(int i=0; i<numbers.size(); i++)
{
if(data.find(target - numbers[i])!=data.end())
{
if(i != data[target-numbers[i]])
{
res.push_back(i);
res.push_back(data[target-numbers[i]]);
break;
}
}
}
if(res.size() == 2)
{
if(res[0] > res[1])
{
int temp = res[0];
res[0] = res[1];
res[1] = temp;
}
}
return res;
}
};