My solution using c++11


  • 0
    S
    class Solution {
    public:
    int removeElement( vector<int> &nums, int val ) {
        int cnt = count( nums.cbegin(), nums.cend(), val );
        if( cnt == 0 ) {
            return nums.size();
        }
        
        const int length = nums.size() - cnt;    
        vector<int> indexes;
        for( int i = 0; i < length; ++i ) {
            if( nums[i] == val ) {
                indexes.push_back( i );
            }
        }
        int j = nums.size();
        for( auto index : indexes ) {
            while( nums[--j] == val ) 
            {  }
            nums[index] = std::move( nums[j] );
        }
        return length;
    }
    };

Log in to reply
 

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