given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
std::vector<int> twoSum(std::vector<int>& nums, int target)
{
for (int i=0;i<nums.size();i++)
{
for (int j = i+1; j<nums.size();j++)
{
if (nums[i] + nums[j] == target)
{
return std::vector<int>{i, nums[i], j, nums[j]};
}
}
}
}
std::vector<int> twoSum2(std::vector<int>& nums, int target){
std::map<int, int> numMap;
for (int i=0;i<nums.size();i++)
{
int num = target - nums[i];
if (numMap.count(num)){
return {numMap[num], i}; // 先入的下标更小
}
numMap[nums[i]] = i;
}
return {};
}