I'm at a loss. I am trying to sum two numbers of vector such that they equal target, then return their indices; however, when running the code with a C 11 for-loop, the result is incorrect. With vector [2,7,11,15] and target=9, the result for the C 11 loop is [0, 0]. Using the C-style loop, it is [0,1]. What gives?
class Solution {
public:
vector<int> twoSumCstyle(vector<int>& nums, int target) {
vector<int> sol(2);
bool found = false;
for (int i = 0; i< nums.size()-1; i ){
for ( int x = i 1; x <nums.size(); x ){
if (nums[i] nums[x] == target) {
sol[0] = i;
sol[1] = x;
found = true;
break;
}
}
if (found) break;
}
return sol;
}
vector<int> twoSumC11(vector<int>& nums, int target) {
vector<int> sol(2);
bool found = false;
for (int i : nums ){
for ( int x = i 1; x <nums.size(); x ){
if (nums[i] nums[x] == target) {
sol[0] = i;
sol[1] = x;
found = true;
break;
}
}
if (found) break;
}
return sol;
}
};
CodePudding user response:
Your outer loop is setting i
to the actual value within your nums
vector, but your inner loop is using it as if it's an index! As an explicit example, on the first iteration of your outer loop, i
will be 2
and so your inner loop will start at x : 3
.
Since you're actually interested in the index as part of your calculations, it probably just makes the most sense to use the traditional-style for-loop.