Friday, 8 April 2016

LeetCode - Two Sum Problem Solution.

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.
Example:


Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

Solution:

#include <bits/stdc++.h>
using namespace std;
/*
    *
    * Prosen Ghosh
    * American International University - Bangladesh (AIUB)
    *
*/
class Solution { public: vector<int> twoSum(vector<int> nums, int target) { vector<int>tmp; for(int i = 0; i < nums.size()-1; i++){ for(int j = i+1; j < nums.size(); j++){ if(nums[i] + nums[j] == target){ tmp.push_back(i); tmp.push_back(j); return tmp; } } } return tmp; } }; int main() { Solution s; vector<int>tmp; tmp = s.twoSum({2, 7, 11, 15},9); cout << "["; for(int i = 0; i < tmp.size(); i++){ cout << tmp[i]; if(tmp.size()-1 != i)cout << ","; } cout << "]" << endl; return 0; }

No comments:

Post a Comment