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;
}
};
Aucun commentaire:
Enregistrer un commentaire