C++ 4ms Very Elegant


  • 3
    R
    int removeElement(vector<int>& nums, int val) 
    {
        size_t idx(0);
        for (const int num : nums)    
        {
            if ( num != val)
                nums[idx++] = num;
        }
        
        return idx;
    }

  • 0
    A

    Please can you explain the code.I want to learn how to think to solve a problem.


  • 0
    R

    In order to understand the above solution try to understand this simpler one

     int removeElement(vector<int>& nums, int val) 
        {
            vector<int> result;        
            for (const int num : nums)    
            {
                if ( num != val)    
                    result.push_back(num);
            }
            
            nums = result;
            return nums.size();
        }
    

    After you understand the above you will understand the original solution.
    The difference is that instead of copying elements to a 'result' vector skipping the duplicates we copy back to the nums beginning. Its a common technique to use the input vector/array as a result if you don't need to use it again in the future. The reason it works is that every element that we overwrite has been already processed.


  • 0
    A

    And i, at the beginning i plan to keep into a vector different values from val but what
    I do not understand why return the idx in first algorithm and result.size () (ie the vector size )in the second?
    What is the difference between idx++ and ++idx?


Log in to reply
 

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