--DAY 7--
Hi, I am going to make #100DaysOfCode Challenge. Everyday I will try solve 1 problem from leetcode or hackerrank. Hope you can go with me until end.
Now let's solve problem today:
-Problem: Remove Element
-Detail: https://leetcode.com/problems/remove-element/
-My solution (javascript):
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;
};
-->If you have better solution or any question, please comment below. I will appreciate.
Top comments (2)
I think you should change
return i
toreturn nums.splice(--i).length
since if you run this function over the same array multiple times, it can eventually start putting formerly-removed elements back into the array (or work on an array whose "real length" should be 0 long ago) since subsequent iterations will traverse all the way to original indexN
, when the length should beN-i
each time. In a language that can't resize an array, like C for example, this would be accomplished by placing a null byte at indexi
to stop traversal at the new length on subsequent runs.Edit: it just occurred to me that in C, null-termination is a thing for character arrays (strings) and other such potentially variable-length arrays, and not for every array, like ints. It only would matter if code that iterates over the array will check for and stop on a null byte. Otherwise, returning the number of erased elements should be enough, since it should be calling code's responsibility to subtract that from wherever the array's length is recorded.
I only code by js, so i dont know that. Thank you!