Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The relative order of the elements may be changed.
The goal of this challenge is to remove all occurrences of a specified value in an integer array, without creating a new array. The relative order of the elements may be changed. This technique is known as "in-place" modification.
Here's a JavaScript solution to this problem:
var removeElement = function(nums, val) {
let i = 0;
for(let j = 0; j<nums.length; j++){
if(nums[j]!==val){
nums[i]=nums[j]
i++
}
}
return i
};
Let's break down the code and understand how it works:
We declare a variable
i
and initialize it to0
. This variable will keep track of the position in the array where the next non-matching element should be placed.We have a for loop that starts at index
0
and goes up to the length of thenums
array. The variablej
will keep track of the current index we're checking in thenums
array.In the loop, we check if the current element in the
nums
array,nums[j]
, is equal to the specified value val.If the current element does not match the specified value, we copy it over to the current position in the array being tracked by
i
. This effectively removes the occurrence of the specified value.Finally, we increment
i
by 1, ready to copy over the next non-matching element.When the loop ends, the
i
variable will hold the length of the new array after all the occurrences of val have been removed.
And that's it! With this simple code, we can remove all occurrences of a specified value from an array in-place, changing the relative order of the elements in the process if necessary.
Top comments (0)