[Leetcode c++] Remove Element

Problem

Given an array and a value, remove all instances of that value in place and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

The order of elements can be changed. It doesn’t matter what you leave beyond the new length.

Example:
Given input array nums = [3,2,2,3], val = 3

Your function should return length = 2, with the first two elements of nums being 2.

Solution

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int l = 0;
        int r = nums.size()-1;
        int count = 0;
        
        while(l <= r){
            //replace the left repeated value with rightest value
            if(nums[l] == val){
                nums[l] = nums[r];
                r--;
            }else{
                l++;
                count++;
            }
        }
        
        return count;
    }
};

Analysis

We scan the array from leftside, and replace every target value with the value from the rightside. In specific
– for nums[left] == val, we have nums[left] = nums[right], right–
– for nums[left] != val, we have left++

Time complexity: O(n), where n in the length of the array

Leave a Reply

Your email address will not be published. Required fields are marked *

*