提问人:Funmi Orekoya 提问时间:9/3/2021 最后编辑:Adrian MoleFunmi Orekoya 更新时间:9/3/2021 访问量:1762
信号:中止(核心转储),从向量形成一个二和对
signal: aborted (core dumped), making a two sum pair from a vector
问:
这是我试图解决的问题:
Write ,它接受一个整数向量和 target sum,并返回表示两个不同索引的对 总和为目标值的元素(对索引进行排序)。 这里没有明确的时间复杂度约束(即算法 只需要按预期工作)。此外,请确保处理空输入。
findTwoSumPair
这是我的主要:
std::cout << "Q3" << std::endl;
std::vector<int> q3Input1{0, 2, 3, 4, 5};
std::pair<int, int> q3Out1 = findTwoSumPair(q3Input1, 6);
std::pair<int, int> q3Out2 = findTwoSumPair(q3Input1, 10);
std::cout << q3Out1.first << " " << q3Out1.second
<< std::endl; // should output 1 3
std::cout << q3Out2.first << " " << q3Out2.second
<< std::endl; // should output -1 -1
这是导致我问题的功能:
std::pair<int, int> findTwoSumPair(const std::vector<int>& vec, int targetSum) {
for (unsigned int i = 0; i < vec.size(); i++){
for(unsigned int j = i; i < vec.size();j++){
/*
if(targetSum == vec[i]+ vec[j]){
std::cout << vec[i] << vec[j];
}*/
}
}
return{vec[i],vec[j];
// throw std::logic_error("not implemented");
}
我得到了main.cpp,所以我不想改变它,并且有相关的库头可以让它运行。
由于某种原因,它只显示“Q3”。我注释掉了块内的内容,因为这给了我“信号:中止(核心转储)”错误。if
答:
0赞
Adrian Mole
9/3/2021
#1
除了代码中的“错别字”之外,您在内部循环中进行测试,而不是(您当前拥有的代码将永远运行该内部循环),您的函数中还有一些其他问题。i
for
j
首先,该内部循环应从 开始,否则当任何一个值正好是目标的一半时,将找到匹配项(在第二个测试用例中,它将找到 的匹配项,给出 和 的索引结果)。j = i + 1
5 + 5
4
4
其次,一旦找到匹配项,函数就应该返回当前和值;然后,如果外部环路在没有找到匹配项的情况下终止,我们可以返回所需的信号。i
j
{-1, -1}
以下是修复了上述(和其他一些)问题的函数版本:
std::pair<int, int> findTwoSumPair(const std::vector<int>& vec, int targetSum)
{
for (size_t i = 0; i < vec.size(); i++) {
for (size_t j = i + 1; j < vec.size(); j++) {// Start at i + 1 and test j (not i)
if (targetSum == vec[i] + vec[j]) {
return{ static_cast<int>(i), static_cast<int>(j) }; // Match found
}
}
}
return { -1, -1 }; // Not found.
}
评论
targetSum
vec
two distinct indices