Coo*_*oli -3 c++ iteration vector time-limiting
我正在寻找有关矢量迭代的一些提示.我正在尝试完成一个挑战,你必须实现一个函数(SumOfTwo),它接受两个向量和一个和作为参数,并且必须检查两个向量中是否有任何数字对,如果添加可以给出总和作为参数传递.
我的功能很好,除了它不包括500毫秒的时间限制.我觉得有一个更好的方法来迭代两个向量而不是两个for循环,但我觉得非常卡住......
bool sumOfTwo(std::vector<int> a, std::vector<int> b, int v) {
if((a.empty()) || b.empty()){
return false;
}
for (std::vector<int>::iterator it1 = a.begin(); it1<=a.end(); ++it1) {
for (std::vector<int>::iterator it2 = b.begin(); it2<=b.end(); ++it2) {
if ((*it1 + *it2) == v){
return true;
}
}
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
关于风格提示,请将代码更改为以下内容(为了提高效率和整洁度)
bool sumOfTwo(const std::vector<int>& a, const std::vector<int>& b, int v) {
for (auto i1 : a) {
for (auto i2 : b) {
if ((i1 + i2) == v){
return true;
}
}
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
考虑使用std::unordered_set
和交叉引用来查找是否可以获得最大效率.请记住,a中的查找std::unordered_set
是O(1)
归档时间: |
|
查看次数: |
1224 次 |
最近记录: |