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

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

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.

  • Example
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

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,452评论 0 10
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,959评论 0 23
  • 大家都知道,经常走路对身体有好处,可你也许不知道,走路对心理也有好处。最近,煎蛋网就整理了关于走路的科学研究成果。...
    dctxf阅读 534评论 1 1
  • 《方寸》首演于2017北京国际青年戏剧节,之后精彩剧照由导演李凝画成油画
    凌云焰的李凝阅读 162评论 0 3
  • 或许是昨天晚上积累了一些情绪,今天早上孩子洗刷完之后说要我教她读拼音,说今天中午老师要检查,检查读不出来就...
    远远_d1f1阅读 199评论 0 3