Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target

Interview

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target

Here is  a brute force solution:




#include <iostream> 
#include <vector> 
using namespace std;
class Solution { 
public: 
vector<int> twoSum(vector<int>& nums, int target)  {
 int n = nums.size(); 
for (int i=0;i<n;++i) 
for(int j=0;j<n;++j) if(i!=j) if (nums[i] + nums[j] == target) { vector<int> ret{ i,j };
 return ret;
 } 
} 
}; 
int main() 
{
 int target = 7;
 vector<int> nums{ 1,2,3,4 }; vector<int> ret; 
 Solution Sol1;
 ret = Sol1.twoSum(nums, target); 
 cout << "Solution is "; 
 for (auto i = ret.begin(); i != ret.end(); ++i) std::cout << *i << ' '; 
}
Select the fields to be shown. Others will be hidden. Drag and drop to rearrange the order.
  • Image
  • SKU
  • Rating
  • Price
  • Stock
  • Availability
  • Add to cart
  • Description
  • Content
  • Weight
  • Dimensions
  • Additional information
Click outside to hide the comparison bar
Compare