问题:给定一个整数数组,返回两个数字的索引,使它们加起来成为一个特定的目标
解决方案-
- 将总和复制到cpy
- 对cpy进行排序以便以后进行二进制搜索
- 迭代cpy
- 搜索目标-current_no
- 如果存在于cpy中
- 获取原始矢量nums中的索引
- 将索引附加到结果向量并返回结果向量
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int>cpy;
vector<int>result(2);
result[0] = 0;
result[1] = 0;
int indx = 0;
for(indx = 0; indx < nums.size(); ++indx)
{
cpy[indx] = nums[indx];
}
// sorting to enable binary search on vector later on
sort(cpy.begin(), cpy.end());
int x, y;
bool ispresent;
vector<int>:: iterator base1;
vector<int>:: iterator it2;
base1 = nums.begin();
for(indx = 0; indx < cpy.size(); ++indx)
{
x = cpy[indx];
y = target - x;
// sing bin search to make search time faster
ispresent = binary_search(cpy.begin() + indx, cpy.end(), y);
if(ispresent)
{
cout << "found" << endl;
// fiding index of x, y in original vector nums
result[0] = find(nums.begin(), nums.end(), x) - base1;
result[1] = find(find(nums.begin(), nums.end(), x) + 1, nums.end(), y) - base1;
break;
}
}
return result;
}
};
int main()
{
int n;
cin >> n;
vector<int> v(n);
for(int i = 0; i < n; ++i)
{
cin >> v[i];
}
int target;
cin >> target;
Solution ob;
vector<int>res = ob.twoSum(v, target);
cout << res[0] << " " << res[1] << endl;
return 0;
}
简单地说,您正在向cpy
向量写入值,但它的大小为零。
有一种非常简单的方法可以复制矢量,只需使用=
。
vector<int> cpy = nums;
这就是你所需要的。你不需要你写的for循环。