-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwo-Sum.cpp
More file actions
24 lines (20 loc) · 704 Bytes
/
Two-Sum.cpp
File metadata and controls
24 lines (20 loc) · 704 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
// optimal using hash map t.c=O(N),S.C=O
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> hashh;
// First loop: store all values with their indices
for (int i = 0; i < nums.size(); i++) {
hashh[nums[i]] = i;
}
// Second loop: check for complement
for (int i = 0; i < nums.size(); i++) {
int complement = target - nums[i];
// Check if complement exists and is not the same index
if (hashh.find(complement) != hashh.end() && hashh[complement] != i) {
return {i, hashh[complement]};
}
}
return {};
}
};