-
-
Notifications
You must be signed in to change notification settings - Fork 7.8k
Expand file tree
/
Copy path1.cpp
More file actions
27 lines (24 loc) · 788 Bytes
/
1.cpp
File metadata and controls
27 lines (24 loc) · 788 Bytes
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
/*
* Given an array of integers nums and an integer target, return indices of the
* two numbers such that they add up to target.
* You may assume that each input would have exactly one solution, and you may not use the same element twice.
*/
#include <vector>
#include <unordered_map>
class Solution {
public:
std::vector<int> twoSum(std::vector<int>& nums, int target) {
std::unordered_map<int, int> mp; // value:index
std::vector<int> res;
for (int i = 0; i < nums.size(); i++) {
int diff = target - nums[i];
if (mp.find(diff) != mp.end()) {
res.push_back(mp[diff]);
res.push_back(i);
return res;
}
mp[nums[i]] = i;
}
return res;
}
};