C++ 4ms simple solution

  • 1
    class Solution {
    int removeElement(vector<int>& nums, int val) {
        return solution1(nums, val);
    int solution1(vector<int> &nums, int val){
        for(int i = 0; i < nums.size();){
            if(nums[i] == val) nums.erase(nums.begin() + i);
            else i++;
        return nums.size();

  • 0

    Hmm, everything is good except you have to move every single following element in the vector whenever "erase" is called.

  • 0

    Thanks for letting me know. I thought I have to delete the elements because I did not notice that the problem doesn't care about elements beyond the length.

Log in to reply

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