Share C++/C# (4ms/484) simple explained solution


  • 0
    O

    C++ version

    int removeElement(vector<int>& nums, int val) {
        if(nums.size() == 0)
            return 0;
       int remid = -1; // index of element to remove
       for(int i=0; i <nums.size(); ++i)
       {
           if(nums[i] == val)
           {
               // Initialize remove element index or skip the element
               if(remid == -1)
                remid = i;
           }
           else if(remid != -1)
           {
               // Overwrite remove element place
               nums[remid++] = nums[i];
           }
       }
       
       // Return the remid or the current size if the value was never found
       return remid != -1 ? remid:nums.size();        
    }
    

    C# version

    public int RemoveElement(int[] nums, int val) {
        if(nums == null || nums.Length == 0)
        return 0;
       int remid = -1; 
       for(int i=0; i <nums.Length; ++i)
       {
           if(nums[i] == val)
           {
               if(remid == -1)
                remid = i;
           }
           else if(remid != -1)
           {
               nums[remid++] = nums[i];
           }
       }
       
       return remid != -1 ? remid:nums.Length;
    }

Log in to reply
 

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