题目
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int>::iterator i,j;
vector<int> Index;
bool GotIndex = false;
for (i = nums.begin(); i!=(nums.end() - 1);++i)
{
for(j = (i + 1);j!=nums.end();++j)
{
if (*i + *j == target)
{
Index.push_back(distance(begin(nums), i));
Index.push_back(distance(begin(nums), j));
GotIndex = true;
break;
}
}
if (GotIndex) break;
}
return Index;
}
};
需要两个break跳出循环,其实可以用while来写的
vector.push_back() //向容器的末尾增加内容
Index.push_back(distance(begin(nums), i)); //返回下标, 从现在的迭代器的地址到起始位置的距离
参考
vector<int> bills{ 5, 10, 10, 10, 20 };
vector<int>::iterator iter = find(bills.begin(), bills.end(), 10);
auto index = distance(begin(bills), iter); //返回找到目标值(10)的第一个索引,这里即为1```