力扣算法--求两数之和等于目标数
1.针对无序序列
两个for循环遍历,找到相等的即退出,解析有说用哈希表,还没有掌握
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int>ans;
int n = nums.size();
bool flag = false;
for(int i = 0;i<n-1;i++)
{
for(int j = i+1;j<n;j++)
{
if(target==(nums[i]+nums[j]))
{
flag = true;
ans.push_back(i);
ans.push_back(j);
break;
}
}
if(flag)
{
break;
}
}
return ans;
}
};
2.针对有序序列
思路:采用双向指针,如果最小值+最大值<目标数,指针往后走即left++;如果最小值+最大值>目标数,指针往前走即right–;如果找到相等的就输出下标,因为题目说从1开始所以记得+1.
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int n = numbers.size();
int left = 0;
int right = n-1;
vector<int> ans;
for(int i=0;i<numbers.size();i++)
{
if(target==(numbers[left]+numbers[right]))
{
ans.push_back(left+1);
ans.push_back(right+1);
break;
}
if(target>numbers[left]+numbers[right])
{
left++;
}
if(target<numbers[left]+numbers[right])
{
right--;
}
}
return ans;
}
};