twoSum
来源:3-7 滑动窗口 Minimum Size Subarray Sum
慕数据7421358
2020-05-26
bobo老师,我在twoSum题目中自己用了测试用例,但是程序跑不通,应该是在twoSum()函数返回值赋值给新的vector容器里出错了,就是我下面注释的那一行,这个问题的原因是什么,该怎么解呢?
int main() {
int arr[] = { 1,3,8,9,4,5,2 };
vectorvec(arr, arr + sizeof(arr) / sizeof(int));
vectorc = twoSum(vec, 3); //函数return vector(res, res + 2);
for (int i = 0; i < c.size(); i++) {
cout << c[i] << " ";
}
cout << endl;
return 0;
}
2回答
-
慕数据7421358
提问者
2020-05-26
#include<iostream>
#include<vector>
#include<cassert>
#include<stdexcept>
//125,344,345,11
using namespace std;
vector<int> twoSum(vector<int>& numbers, int target) {
int l = 0, r = numbers.size() - 1;
while (l < r) {
if (target == numbers[l] + numbers[r]) {
int res[2] = { l + 1,r + 1 };
return vector<int>(res, res + 2);
}
if (target > numbers[l] + numbers[r]) {
l++;
}
if (target < numbers[l] + numbers[r]) {
r--;
}
}
throw invalid_argument("The input has no solution.");
}
int main() {
int arr[] = { 1,3,8,9,4,5,2 };
vector<int>vec(arr, arr + sizeof(arr) / sizeof(int));
vector<int>c = twoSum(vec, 3);
for (int i = 0; i < c.size(); i++) {
cout << c[i] << " ";
}
cout << endl;
return 0;
}
00 -
liuyubobobo
2020-05-26
给我完整的可执行代码?
022020-05-26
相似问题
回答 1