Day3. Remove Element(27)
2017-11-06 本文已影响0人
前端伊始
问题描述
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 by modifying the input array in-place with O(1) extra memory.
Example
Given nums = [3,2,2,3], val = 3,
Your function should return length = 2, with the first two elements of nums being 2.
注意:每次删除一个元素时,注意数组下标的变化
/**
* @param {number[]} nums
* @param {number} val
* @return {number}
*/
var removeElement = function(nums, val) {
for(var i = 0; i < nums.length; i++){
if(nums[i] == val){
nums.splice(i,1);
i-=1;
}
}
return nums.length;
};
文末彩蛋
Day3. Remove Element(27)