One reason you may not be able to print on one line is if the type of elements held in the std::vector result already have a stream insertion operator overload defined with a newline character in it
//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> result(2);
for (int i = 0; i < nums.size(); i++) {
for (int j = i + 1; j < nums.size(); j++) {
if(nums[i]+nums[j] == target)
{
result[0] = i;
result[1] = j;
return result;
}
}
}
return result;
}
};
//vector<int> twoSum(vector<int> &numbers, int target)
//{
// //Key is the number and value is its index in the vector.
// unordered_map<int, int> hash;
// vector<int> result;
// for (int i = 0; i < numbers.size(); i++) {
// int numberToFind = target - numbers[i];
//
// //if numberToFind is found in map, return them
// if (hash.find(numberToFind) != hash.end()) {
// //+1 because indices are NOT zero based
// result.push_back(hash[numberToFind] + 1);
// result.push_back(i + 1);
// return result;
// }
//
// //number was not found. Put it in the map.
// hash[numbers[i]] = i;
// }
// return result;
//}
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
These restrictions have to be borne in mind and also a single function can replace class Solution:
#include <iostream>
#include <vector>
#include <iterator>
std::vector<size_t> twoSum(const std::vector<int>& nums, constint target)
{
std::vector<size_t> result(2, 0);
bool match = false;
for (auto itr_trail = nums.cbegin(); itr_trail != nums.cend(); ++itr_trail)
{
for (auto itr_lead = itr_trail + 1; itr_lead != nums.cend(); ++itr_lead)
{
if( (*itr_lead) != (*itr_trail))
//you may not use the same element twice
{
if((*itr_lead) + (*itr_trail) == target)
{
result[0] = std::distance(nums.cbegin(), itr_trail);
//search if unfamiliar
result[1] = std::distance(nums.cbegin(), itr_lead);
match = true;
break;
//assume each input has exactly one solution ...
// ... so we can break after finding one solution
}
}
}
if (!match)std::cout << "No match found \n";
return result;//[0,0] (i.e. no match) only case when both elements are same
}
}
int main()
{
std::vector<int> nums {2, 7, 11, 15};
int target = 9;
for (constauto& elem : twoSum(nums, target))std::cout << elem << " ";
}