Remove Elements Runtime error


  • 1
    X

    class Solution {
    public:
    int removeElement(vector<int>& nums, int val) {
    if (nums.size()==0)
    return 0;

        int counter = 0;
        
        for(int i = 0; i<nums.size(); i++){
            if(nums[i]==val)
                counter++;
        }
        
        if (counter==0)
            return nums.size();//edge case, no element == val
    
    
        if (counter==1){
            for(int i=0;i<nums.size();i++){
                if(nums[i]==val){
    
                    int temp =0;
                    temp = nums[nums.size()-1];
                    nums[nums.size()-1] = nums[i];
                    nums[i]= temp;
                }
            
            }
            return nums.size()-1;
        }
            
        int front = 0;
        int end = nums.size()-1;
        
        while(end!=nums.size()-counter-1)
        {
            if(nums[front]!=val){
                front++;
            }
            
            if(nums[end]==val){
                end--;
            }
            //swapping
            int temp = nums[end];
            nums[end] = nums[front];
            nums[front] = temp;
            
        }         
        return (nums.size()-counter);
    }   
    

    };

    my code gives me the correct output but it has runtime error when the input vector is [3,3] and the value is 5. Can someone help me?


  • 0
    S

    the same problem with you, please tell me if you figure it out.


Log in to reply
 

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