Please check the link first for the details of the problem.
Remove Element
Given an array
nums
and a valueval
, 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 by modifying the input array in-place with O(1) extra memory. The order of elements can be changed. It doesn't matter what you leave beyond the new length.Given
nums = [3,2,2,3], val = 3
, your function should return length = 2, with the first two elements ofnums
being 2. It doesn't matter what you leave beyond the returned length.
The first thought to this problem was a naive solution — to create another array for filtered values. However, under the requirement of memory usage. We have to modify the input array in place.
The output should be a number N which represents the valid length of the array, which means the first N elements should not have the val
.
I decided to use two pointer method to solve this problem.
- [ ] Why?
With two pointers
index
,targetIndex
,index
representing the index ofnums
loop function andtargetIndex
representing the result array index which starts from 0. Imagine you are operating a new array based on the original array, you are just moving the qualified values forward into the new array. In the loop ofnums
, ifnums[index]
is not equal toval
, we move the values to the new array,nums[targetIndex] = nums[index]
and increment thetargetIndex
by 1 to expand the new array. Ifnums[index]
is equal toval
we just skip the the value movement, so the new array will only include the qualified values.
/**
* @param {number[]} nums
* @param {number} val
* @return {number}
*/
var removeElement = function(nums, val) {
const arrLength = nums.length;
if (arrLength === 0)
return 0;
let targetIndex = 0;
for(let index = 0; i < arrLength; index++) {
if (nums[index] !== val)
nums[targetIndex++] = nums[index];}
return targetIndex;
};
Top comments (0)