C++ without < comparison


  • 0
    M

    Other shorter solutions have taken advantage of using operator < on the input sequence -- which seems appropriate for this question. I was thinking that the std::unique() function in the c++ standard library only requires comparison for equality, so I attempted to code under the same restriction. I see now that the others have also done/posted similar solutions:

            int removeDuplicates(vector<int>& nums)
            {
                auto N = static_cast<int>(nums.size());
                if (N < 2)
                    return N;
    
                auto iter = begin(nums);
                auto last = end(nums);
    
                auto dupe = false;
                for (auto jter = ++iter; jter != last; ++jter)
                {
                    // copy if adjacent items are different or not duplicated
                    auto same = (jter[-1] == jter[0]);
                    if (! same || ! dupe)
                    {
                        *iter++ = *jter;
                    }
                    
                    dupe = same;
                }
    
                return distance(begin(nums), iter);
            }
    

Log in to reply
 

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