-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwoSum.cpp
More file actions
45 lines (44 loc) · 1.06 KB
/
Copy pathTwoSum.cpp
File metadata and controls
45 lines (44 loc) · 1.06 KB
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
//brute force (using two loops)
//Time Complexity :O(n^2)
//Space Complexity :O(1)
class Solution
{
public:
vector<int> twoSum(vector<int> &nums, int target)
{
int n = nums.size();
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (nums[i] + nums[j] == target)
{
return {i, j};
}
}
}
return null;
}
}
// Optimal Solution
// Time Complexity : O(n)
// Space Complexity : O(n)
class Solution
{
public:
vector<int> twoSum(vector<int> &nums, int target)
{
unordered_map<int, int> numMap; // map for {element,index of array}
for (int i = 0; i < nums.size(); i++)
{
int complement = target - nums[i];
if (numMap.find(complement) != numMap.end())
{
return {numMap[complement], i};
}
numMap[nums[i]] = i;
}
// In case there is no solution, we'll just return an empty vector
return {};
}
};