思路:
(1)暴力求解:时间复杂度o(n^2)
(2)二分优化:时间复杂度o(logn),空间复杂度(nlogn)
(3)哈希表:时间复杂度o(n),空间复杂度(n)
(4)双指针:时间复杂度o(n),空间复杂度(1)
(1)暴力求解
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)二分优化
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)哈希表
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)双指针
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 };
}
};