Only one 'for' loop C++ solution


  • 1
    T

    There should be only one 'for' loop. One uses hash map only for getting the first index.

    std::vector< int > twoSum( std::vector< int > & nums, int target )
    {
        std::map< int, int > value_to_index;
    	std::vector< int > out;
    	for( unsigned int i = 0; i < nums.size(); ++i )
    	{
    		if( value_to_index.count( target - nums[i] ) )
    		{
    		    out.push_back( value_to_index[target - nums[i]] );
    		    out.push_back( i + 1 );
    		    break;
    		}
    		value_to_index[nums[i]] = i + 1;
    	}
    	return out;
    }

  • 0
    S

    std::map is not hash map. It's a red-black tree.
    std::unordered_map is hash map.


Log in to reply
 

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