1. Two Sum
- Brute-force
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 {};
}
};
-
T:
-
S:
-
HashMap
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target)
{
int n = nums.size();
unordered_map<int, int> m;
for (int i = 0; i < n; ++i)
{
int complement = target - nums[i];
if (m.count(complement)) return {i, m[complement]};
m[nums[i]] = i;
}
return {};
}
};
- T:
- S: