Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
#include <iostream>
#include <vector>
using namespace std;
class Solution
{
public:
vector<int> twoSum(vector<int>& nums, int target)
{
vector<int> Rect;
int i = 0, j = 0;
for(i = 0; i < nums.size() - 1; i++)
{
for(j = i+1; j < nums.size(); j++)
{
if(nums[j] == (target - nums[i]))
{
Rect.push_back(i);
Rect.push_back(j);
return Rect;
}
}
}
return Rect;
}
};
int main(int argc, _TCHAR* argv[])
{
int NumArray[4] = {2, 7, 11, 15};
int ArrayIndex = 0;
Solution a;
vector<int> nums;
vector<int> RectVector;
while(ArrayIndex < 4)
{
nums.push_back(NumArray[ArrayIndex]);
ArrayIndex++;
}
RectVector = a.twoSum(nums, 9);
cout << RectVector[0] << endl;
cout << RectVector[1] << endl;
system("pause");
return 0;
}