QUESTION:
Given an array of integers nums
and an integer target
, return indices of the two numbers such that they add up to target
.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
if needed more you can visit the questions = (https://leetcode.com/problems/two-sum/description/)
I have solved this question with brute force solution however i am facing issues in c++ concept or maybe some basic interpretting issue.
My code:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int n = nums.size();
vector<int> ans;
for ( int i = 0; i < n; i++){
for ( int j = i+1; j < n ; j++){
if ( nums[i] + nums[j] == target){
ans.push_back(i);
ans.push_back(j);
return ans;
}
}
}
}
};
However this solution is not showing compiling error =
Line 16: Char 5: error: non-void function does not return a value in all control paths [-Werror,-Wreturn-type]
16 | }
| ^
1 error generated.
So I prepared another solution which is working but i cant figure out the reason why the previous code is not working and this is.
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int n = nums.size();
vector<int> ans;
for ( int i = 0; i < n; i++){
for ( int j = i+1; j < n ; j++){
if ( nums[i] + nums[j] == target){
ans.push_back(i);
ans.push_back(j);
}
}
}
return ans;
}
};
Somebody please explain the logic.
edit: i have done the dry run and for every input it is necessary that if ( nums[i] + nums[j] == target)
will be executed and a return value will be given
picki_panda is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1