Multimap Based Solution


  • 0
    N
        vector<int> twoSum(vector<int>& nums, int target) {
            vector<int> returnValues;
            multimap<int, int> numsHash;
            
            for (int i = 0; i < nums.size(); i++) {
                numsHash.insert(std::pair<int,int>(nums[i],i)) ;
            }
            
            std::multimap<int, int>::iterator startIter = numsHash.begin();
            std::multimap<int, int>::iterator endIter = --numsHash.end();
    
            while (startIter != endIter) {
                int possible = (startIter->first + endIter->first);
    
                if (target < possible) {
                    endIter--;
                }
                else if (target > possible) {
                    startIter++;
                }
                else {
                    returnValues.push_back(startIter->second);
                    returnValues.push_back(endIter->second);
                    break;
                }
            }
            
            return returnValues;
        }
    

Log in to reply
 

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