Simple C++ solution,4ms.


  • 0
    B

    From the beginning number, select the ones equal to 'val' , swap with the tail number.

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

Log in to reply
 

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