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;

}


0
0

liuyubobobo

2020-05-26

给我完整的可执行代码?

0
2
liuyubobobo
回复
慕数据7421358
哈哈。没事儿,继续加油!:)
2020-05-26
共2条回复

玩转算法面试-- Leetcode真题分门别类讲解

课程配套大量BAT面试真题,高频算法题解析,强化训练

7410 学习 · 1150 问题

查看课程