版权声明:转载需转载声明 https://blog.csdn.net/qq_32285693/article/details/83957379
1、Two Sum
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
class Solution
{
public:
vector<int> twoSum(vector<int>& nums, int target)
{
// 定义临时变量返回需要的结果
vector<int> result;
// 进行算法处理
for(int i =0;i<nums.size();i++)
{
for(int j = i+1;j<nums.size();j++)
{
if(nums[i]+nums[j] == target)
{
result.push_back(i);
result.push_back(j);
break;
}
}
}
// 做没有找到的处理 默认返回 -1 -1
vector<int> temp;
temp.push_back(-1);temp.push_back(-1);
if(result.size()==0)
return temp;
// 正常情况下返回得到的结果
return result;
}
};