Ideas:
(1) Violent solution: time complexity o(n^2)
(2) Binary optimization: time complexity o(logn), space complexity (nlogn)
(3) Hash table: time complexity o(n ), space complexity (n)
(4) double pointer: time complexity o(n), space complexity (1)
(1) Violent solution
class Solution
{
public:
vector<int> twoSum(vector<int>& numbers, int target)
{
vector<int>res;
int len1 = numbers.size();
for (int i = 0;i < len1;i++)
{
for (int j = i + 1;j < len1;j++)
{
if (numbers[i] + numbers[j] == target)
return {
i,j };
}
}
return res;
}
};
(2) Binary optimization
class Solution
{
public:
vector<int> twoSum(vector<int>& numbers, int target)
{
vector<int>res;
int len1 = numbers.size();
for (int i = 0;i < len1;i++)
{
int low = i + 1;
int high = len1 - 1;
while (low <= high)
{
int mid = (high - low) / 2 + low;
if (numbers[mid] == target - numbers[i])
return {
i,mid };
else if (numbers[mid] > target - numbers[i])
{
high = mid - 1;
}
else
low = mid + 1;
}
}
return {
-1,-1 };
}
};
(3) Hash table
class Solution
{
public:
vector<int> twoSum(vector<int>& numbers, int target)
{
vector<int>res;
unordered_map<int, int>map;
int len1 = numbers.size();
for (int i = 0;i < len1;i++)
{
if (map.count(target - numbers[i])!=0)
return {
map[target-numbers[i]],i};
map[numbers[i]] = i;
}
return {
-1,-1};
}
};
(4) Double pointer
class Solution
{
public:
vector<int> twoSum(vector<int>& numbers, int target)
{
vector<int>res;
int high = numbers.size()-1;
int low = 0;
while (low < high)
{
if (numbers[low] + numbers[high] == target)
return {
low,high };
else if (numbers[low] + numbers[high] > target)
high--;
else
low++;
}
return {
-1,-1 };
}
};