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.
/**
* @param {number[]} nums
* @param {number} val
* @return {number}
*/
var removeElement = function(nums, val) {
var id = nums.indexOf(val);
while(id !== -1){
nums.splice(id,1);
id = nums.indexOf(val);
}
return nums.length;
};
突然意识到,好像并不是让我用indexOf的,然后就写了第二种解法。
/**
* @param {number[]} nums
* @param {number} val
* @return {number}
*/
var removeElement = function(nums, val) {
var j=0;
var ll = nums.length;
for(var i=0;i<ll;i++){
if(nums[i]!==val){
nums[j]=nums[i];
j++;
}
}
return j;
};