C++ solution

  • 0

    This solution uses hash table ( c++ map ) to store the vector while iterating over it. For every new element in the vector it iterates over, it looks for another number so as to make sum to given value, in the map that been being formed.

        vector<int> twoSum(vector<int>& nums, int target) {
            vector<int> *res = new vector<int>;
            int diff = 0;
            int i=0;
            std::map<int, int> m;
            std::map<int,int>::iterator mi;
            for (std::vector<int>::iterator it = nums.begin(); it != nums.end(); ++it){
                diff = target - *it;
                if(mi = m.find(diff), mi != m.end()){
                m.insert(std::pair<int,int>(*it, i));
            return *res;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.