leetcode --- js版本程序员

leetcode-Easy-第8期-数组类型-Remove El

2019-03-02  本文已影响3人  石头说钱

题目:在不创建新的数组下,移除数组中所有给定的值

Given an array nums and a value val, 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.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.

Given nums = [3,2,2,3], val = 3
移除目标值3数组变成:[2,2]
所以返回长度为2


var removeElement = function(nums, val) {
  const len = nums.length
  for(let i = 0; i < len; i++){
    if(nums[i] !== val){
      nums.push(nums[i])
    }
  }
   nums.splice(0,len)
   return nums.length
  
};

const len = nums.length
  for(let i = 0; i < len; i++){
    if(nums[i] !== val){
      nums.splice(i,1)
    }
  }
   return nums.length

上一篇 下一篇

猜你喜欢

热点阅读