27. Remove Element
Problem
https://leetcode.com/problems/remove-element/
Given an array and a value, 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 in place with constant memory.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
Example:
Given input array nums = [3,2,2,3], val = 3
Your function should return length = 2, with the first two elements of nums being 2.
Solution
Solution1
Take out the matched item every time we meet one. Pretty straight forward, especially with JavaScript.
/**
* @param {number[]} nums
* @param {number} val
* @return {number}
*/
var removeElement = function(nums, val) {
let i
while ((i = nums.indexOf(val)) !== -1) {
nums.splice(i, 1)
}
return nums.length
};
Solution2
Since the order of elements can be changed, we can use the mismatched elements from the tail to fill in the gap in the front.
Gotcha: len could be -1 when all the elements are matched.
/**
* @param {number[]} nums
* @param {number} val
* @return {number}
*/
var removeElement = function(nums, val) {
let len = nums.length
for (let i = 0; i < len; i += 1) {
if (nums[i] === val) {
while (--len > i && nums[len] === val) { }
nums[i] = nums[len]
}
}
return nums.length = len < 0? 0 : len
};