27 Remove Element
Problem Statement
Given an integer array nums
and an integer val
, remove all occurrences of val
in nums
in-place. The order of the elements may be changed. Then return the number of elements in nums
which are not equal to val
.
Instructions
Consider the number of elements in nums
which are not equal to val
be k
, to get accepted, you need to do the following things:
Change the array
nums
such that the firstk
elements of nums contain the elements which are not equal toval
. The remaining elements ofnums
are not important as well as the size ofnums
.Return
k
.
For the whole problem statement, please refer here.
Plans
Use a pointer to keep track of the position to place the next non-val element.
Loop through each element of the input array nums.
If the current element is not equal to val, place it at the pointer's position and increment the pointer.
At the end of the loop, the pointer will indicate how many elements are not equal to val, so return this count.
Solution
Explanation
Initialization
Start by defining a variable
k
that will serve as a pointer to track the index of the next position whre a non-val element should be placed and initiaily,k
is set to 0.
Loop through the elements
Iterate over each element in the list
nums
using a for loop. The loop runs for the lenght of the list, allowing us to check each value.
Condition to check
Inside the loop, check if the current element
nums[i]
is not equal toval
. This condition is crucial as it determines whether we want to keep the current element or remove it.
Place non-val elements
If the condition is true (meaning the element is not eqaul to
val
), assign the value ofnums[i]
tonums[k]
, effectively moving the non-val
element to the front of the array.
Increment pointer
After placing the element, we increment
k
to get ready for the next potential non-val
element.
Return the value of
k
Once the loop completes,
k
will hold the count of the elements that are not equal toval
. We return ths value to indicate how many elements should be considered in the updated array.
Last updated