4ms c++ solution considered that the first and the last are both the same with val


  • 0
    class Solution {
    public:
        int removeElement(vector<int>& nums, int val) {
            int n=nums.size(),i=0;
            if(n==0)return 0;
            while(val==nums[n-1])n--;
            while(i<n){
                if(val==nums[i])
                    nums[i]=nums[--n];
                else
                    i++;
            }
            return n;
        }
    };

Log in to reply
 

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