C++ solution


  • 0
    A

    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.

    public:
        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()){
                    (*res).push_back(mi->second);
                    (*res).push_back(i);
                    break;
                }
                m.insert(std::pair<int,int>(*it, i));
                i++;
            }
            return *res;
        }
    };

Log in to reply
 

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