It isnt cool, but correct to cope with the duplicated numbers C++ using map


  • 0
    vector<int> twoSum(vector<int>& nums, int target)
    {
    	vector<int> result(2);
    	map<int, int> valueIndices;
    	for(vector<int>::size_type i = 0; i != nums.size(); ++i)
    	{
    		int numberToFind = target - nums[i];
    		if(valueIndices.find(numberToFind) != valueIndices.end())
    		{
    			result[0] = valueIndices[numberToFind];
    			result[1] = i;
    			return result;
    		}
    		
    		else if(valueIndices.find(nums[i]) == valueIndices.end())
    		{
    			valueIndices[nums[i]] = i;
    		}
    	}
    	return result;
    }
    

Log in to reply
 

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