Two line C++ solution using STL


  • 0
    R
    class Solution {
    public:
        int removeElement(vector<int>& nums, int val) {
            nums.erase(std::remove(nums.begin(), nums.end(), val), nums.end());
            return nums.size();
        }
    };
    

    Uses Erase-remove idiom, basically cheating and probably not going to get you past the interview ;-)


  • 0

    Yeah, if I were interviewing you, I'd reject you. Because you use erase for no good reason :-P

    int removeElement(vector<int>& nums, int val) {
        return remove(nums.begin(), nums.end(), val) - nums.begin();
    }
    

  • 0
    B

    remove is better.


Log in to reply
 

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