-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path01_two-sum.cpp
49 lines (38 loc) · 991 Bytes
/
01_two-sum.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
38
39
40
41
42
43
44
45
46
47
48
49
// DATE: 27-07-2023
/* PROGRAM: 01_Array - Two Sum
https://leetcode.com/problems/two-sum/
*/
// @ankitsamaddar @2023
#include <iostream>
#include <map>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int, int> hash;
for (int i = 0; i < nums.size(); i++) {
// dif is the required number to sum to target
int dif = target - nums[i];
// check if dif is hashed
if (hash.count(dif) > 0) {
return {hash[dif], i};
}
// store num index
hash[nums[i]] = i;
}
// not found
return {};
}
};
int main() {
int nums[] = {1, 8, 6, 2, 5, 4, 8, 3, 7};
int target = 9;
vector<int> v(nums, nums + sizeof(nums) / sizeof(int));
Solution sol;
vector<int> rem = sol.twoSum(v, target);
for (int val : rem) {
cout << val << " ";
}
return 0;
}