Lonely Integer

  • + 0 comments

    C++ deserves more love :(

    int lonelyinteger(vector<int> a) {
    
        // Use a set to track numbers we've encountered as we iterate through
        set<int> b;
        
        for (int i : a) {
            // If we lookup i and it doesn't return the end iterator
            if( b.find( i ) != b.end() )
            {
                b.erase( i ); // Remove the already encountered integer
            } else {
                b.emplace( i ); // Track encountered integer
            }
        }
        
        // Convert set to vector
        vector<int> b_vect( b.begin(), b.end() );
        
        // There should only be one element left...
        return b_vect.at(0);
    }