原题链接:力扣
这题用到了STL中的vector。vector常用的方法有迭代器以及排序,相关知识点如下:
#include <iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
vector<int> vec = { 1, 3, 4, 2, 5 };
//迭代器
vector<int>::iterator itor;
for ( itor = vec.begin(); itor != vec.end(); itor++)
{
cout << *itor << endl;
}
/*
//使用auto
for (auto i = vec.begin(); i != vec.end(); i++)
{
cout << *i << endl;
}
*/
cout <<"after sort" << endl;
sort(vec.begin(), vec.end());
for (itor = vec.begin(); itor != vec.end(); itor++)
{
cout << *itor << endl;
}
system("pause");
return 0;
}
如果本题求的是数组中的两个元素,而不是索引,本题的解为:
vector<int> twoSum(vector<int>& nums, int target) {
//先排序
sort(nums.begin(), nums.end());
//结果的存放数组
vector<int> res;
for (int i = 0; i < nums.size() - 1; i++)
{
for (int j = i + 1; j < nums.size(); j++){
if (nums[i] + nums[j] == target){
res.push_back(nums[i]);
res.push_back(nums[j]);
return res;
}
if (nums[i]>target || nums[j]>target){
break;
}
}
}
}
但是求的是索引,所以排序会破坏原数组的位置。又要求时间复杂度小于 O(n2)
的算法,不考虑暴力搜索。这里推荐一个适用于快速查找的容器,unordered_map。若要判断一个值是不是在该容器中,使用map.find(value) != mp.end()。find函数返回的是迭代器:iterator find ( const key_type& key )。
#include <iostream>
#include<vector>
#include<algorithm>
#include<unordered_map>
using namespace std;
vector<int> twoSum(vector<int>& nums, int target) {
//结果的存放数组
vector<int> res;
//存放key-value的容器
unordered_map<int, int> map;
unordered_map<int, int>::iterator itor;
for (int i = 0; i < nums.size(); i++)
{
int value = target - nums[i];
if (map.find(value) != map.end()){
//找到了
itor = map.find(value);
res.push_back(itor->second);
res.push_back(i);
return res;
}
//没找到,则添加map
map.insert(make_pair(nums[i], i));
//map.insert(pair<int, int>(nums[i], i));
}
}
int main()
{
vector<int> vec = { 1, 2, 3, 4, 5 };
int target = 7;
vector<int> res =twoSum(vec, target);
cout << res[0] << " " << res[1] << endl;
system("pause");
return 0;
}