This is the question I'm trying to solve:
Write
findTwoSumPair
, which takes in a vector of integers and a target sum, and returns a pair that represents two distinct indices of elements that sum up to the target value (with indexes sorted). There are no explicit time complexity constraints here (i.e. algorithm just needs to work as intended). Also make sure to handle empty input.
This is my main:
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
And this is the function causing me problems:
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");
}
I was given the main.cpp so I'd like to not change it and there are the relevant library headers to make it run.
It only shows "Q3" for some reason. I commented out the content inside the if
block because that was giving me the "signal: aborted (core dumped)" error.
As well as the "typo" in your code, where you are testing
i
in the innerfor
loop instead ofj
(the code you currently have will run that inner loop forever), there are some other issues in your function.First, that inner loop should start at
j = i + 1
, otherwise a match will be found when any one value is exactly half the target (in your second test case, it will find a match for5 + 5
, giving index results of4
and4
).Second, as soon as a match is found, the function should return the current
i
andj
values; then, if the outer loop terminates without a match being found, we can return the required{-1, -1}
signal.Here's a version of your function with the aforementioned (and some other) issues fixed: