Remove Element

Leetcode practice log

Posted by Rui on 07-10-2021
Estimated Reading Time 1 Minutes
Words 262 In Total
Viewed Times

Remove Element

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.

Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.
Return k after placing the final result in the first k slots of nums.

Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.

First Try

The idea is the same as “Remove Duplicates”, since the question require o(1) memory, we can not use .splice(), instead we move the correct elements into the first k slots of the array.
We need two variables to present the traversing process, j is used to walk through the whole array from front to end, i is used to store the desired ones.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* @param {number[]} nums
* @param {number} val
* @return {number}
*/
var removeElement = function(nums, val) {
let result = 0
let i = 0
let j = 0
while(i<nums.length && j<nums.length){
if(nums[j]===val){
j++
}else{
result += 1
nums[i] = nums[j]
i++
j++
}
}

return result
};


If you like this blog or find it useful for you, you are welcome to comment on it. You are also welcome to share this blog, so that more people can participate in it. If the images used in the blog infringe your copyright, please contact the author to delete them. Thank you !