class部分没有问题,在调用的时候不知道出了什么问题
#include<iostream>
#include<algorithm>
using namespace std;
class Solution {
public:
int* thesum(int nums[], int target)
{
int n = sizeof(nums);
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j)//遍历寻找,前后两个比较,相等就是目标然后输出下标
{
if (nums[i] + nums[j] == target) {
return new int[] {i, j};//输出下标
}
}
}
return nums;
}
};
int main()
{
int nums[] = {1,2,3,4};
int target = 5;
Solution s;
cout << s.thesum(nums, target) << endl;
}
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
class Solution
{
public:
vector<int> thesum(vector<int> nums, int target)
{
int n = nums.size();
for (int i = 0; i < n - 1; ++i)
{
for (int j = i + 1; j < n; ++j) //遍历寻找,前后两个比较,相等就是目标然后输出下标
{
if (nums[i] + nums[j] == target)
{
return vector<int>{i, j}; //输出下标
}
}
}
return vector<int>();
}
};
int main()
{
vector<int> nums = {1, 2, 3, 4};
int target = 5;
Solution s;
vector<int> positions = s.thesum(nums, target);
if (!positions.empty())
cout << positions[0] << ' ' << positions[1] << endl;
}
$ g++ -Wall main.cpp
$ ./a.out
0 3
函数返回的是指针,输出的是地址