leetcode地址:链接
-
问题描述:在有序(由小到大)数组中找出两个数,使它们的和为 target。
-
题目分析:
- 当初考虑使用递归,尝试后不能实现。。。
- 使用双指针主要用于遍历数组,两个指针指向不同的元素,从而协同完成任务。
-
c++代码
#include<iostream>
using namespace std;
#include<vector>
class Solution
{
private:
vector<int> src_data;
int target;
public:
Solution(vector<int> data, int target_data):src_data(data),target(target_data)
{}
vector<int> two_sum()
{
vector<int> res;
int i = 0;
int j = src_data.size() - 1;
while (i < j)
{
if (src_data[i] + src_data[j] < target)
i += 1;
else if (src_data[i] + src_data[j] > target)
j -= 1;
else
{
res.push_back(i);
res.push_back(j);
return res;
}
}
return res;
}
};
int main(int argc, char* argv[])
{
vector<int> data = { 2, 7, 11, 15};
int target = 26;
Solution instance(data, target);
vector<int> res = instance.two_sum();
cout<<"The index is :"<< instance.two_sum()[0]<< "," << instance.two_sum()[1]<<endl;
system("pause");
}