1、解题思路
2、所需函数
①vector 常被称作容器, 它提供了自动调整大小的功能,并且支持随机访问元素。
②push_back 是C++中用于在容器的末尾添加元素的函数,常用于向动态数组(如vector)或者动态链表(如list)中添加新的元素。
③sort用于对序列中的元素进行排序。它可以对数组、向量(vector)、链表(list)等容器中的元素进行排序,也可以对普通数组进行排序。
3、代码实现
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class solution
{
public:
vector<int>twosum(vector<int>& a, int t) {
int n = a.size();
vector<int>id;
for (int i = 0; i < n; i++) id.push_back(i);
sort(id.begin(), id.end(), [a, id](int i, int j) {
return a[id[i]] < a[id[j]];
});//使用了sort()函数对整数数组id中的索引进行排序,排序的依据是通过数组a中元素的值来确定的
int l = 0, r = n - 1;
vector<int>temp;//定义一个容器放所求下标
while (l < r) {
int sum = a[id[l]] + a[id[r]];
if (sum == t) {
temp.push_back(id[l]);
temp.push_back(id[r]);
break;
}
else if (sum < t) {
l++;
}
else {
r--;
}
}
return temp;
}
};
int main()
{
vector<int> a = { 2, 7, 11, 15 };
int t = 9;
solution s;
vector<int> result = s.twosum(a, t);
for (int i = 0; i < result.size(); i++) {
cout << result[i] << " ";
}
cout << endl;
return 0;
}