-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtwoSum.cpp
More file actions
37 lines (32 loc) · 887 Bytes
/
Copy pathtwoSum.cpp
File metadata and controls
37 lines (32 loc) · 887 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
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
class Solution {
public:
/*
* Easy simple solution is n^2 time complexity
* ```
* for (i in range(len(nums)))
* for (j in range(i+1, len(nums)))
* if nums[i] + nums[j] == target:
* return result
* ```
*
* But we can improve time complexity by using hashmap that gives o(1) for searching
*/
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> map;
vector<int> result;
for (int i=0; i<nums.size(); i++) {
if (map.find(nums[i]) == map.end()) {
map[target - nums[i]] = i;
} else {
result.push_back(map.at(nums[i]));
result.push_back(i);
break;
}
}
return result;
}
};