01
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int,int> record;
for (int i = 0; i < nums.size(); i++)
{
int rest = target - nums[i];
if (record.find(rest) != record.end())
{
int res[2] = {i,record[rest]};
return vector<int>(res, res + 2);
}
record[nums[i]] = i;
}
throw invalid_argument("the input has no solution");
}
};
15
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> result;
unordered_map<int, int> record;
sort(nums.begin(), nums.end()); //先对数组进行排序
for (int i = 0; i < nums.size(); i++)
record[nums[i]] = i;
for (int i = 0; i < nums.size(); i++)
{
//为了去重
if (i>0 && nums[i] == nums[i - 1]) continue;
for (int j = i + 1; j < nums.size(); j++)
{
//为了去重
if (j>i + 1 && nums[j] == nums[j - 1]) continue;
int rest = 0 - nums[i] - nums[j];
if (rest < nums[j]) continue;
auto it = record.find(rest);
if (it != record.end() && record[rest] != i&&record[rest] != j)
{
int res[3] = { nums[i],nums[j],rest };
result.push_back(vector<int>(res, res + 3));
}
}
}
return result;
}
};