C++ easy to understand solutions.


  • 0
    C
    // tow-pointer solution 
    int removeElement1(vector<int>& nums, int val) {
        int l = 0, r = nums.size()-1;
        while (l<=r) {
            if (val==nums[l]) {
                int tmp = nums[r];
                nums[r] = nums[l];
                nums[l] = tmp;
                r--;
            } else {
                l++;
            }
        }
        return l;
    }
    
    int removeElement(vector<int>& nums, int val) {
        int i = 0;
        for (auto& num: nums)
            if (num != val)
                nums[i++] = num;
        return i;
    }

Log in to reply
 

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