Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target
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 << ' ';
}
Related Posts
Binary Search in C++
November 15, 2020
5 views
Program to reverse a string
November 14, 2020
19 views
Why cannot you resize an array in C++?
November 7, 2020
8 views
Can you implement a jagged array in C/C++?
November 7, 2020
15 views
Determining if a particular string has all unique characters (in C++)
November 7, 2020
9 views
Search