Day3. Remove Element(27)

问题描述
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;
};

文末彩蛋


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

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,916评论 0 23
  • 李峰把车停在路边“小美,我对你,你应该也知道的对不对。”小美知道李峰的意思,但是不知道他会突然这样表白“嗯...
    半秋伴夏阅读 159评论 0 0
  • 最近没有好好照顾头发,于是它表示了小小的不满。头发有点分叉,而我特别容忍不了这种情况,刚好今早没课,我就去稍微剪了...
    自习女孩冲鸭阅读 409评论 0 1
  • 1 每一次去郑州,对我来说都是一次放风。一周五天,我似待在一个孤岛上,不与外界接触,活动范围局限在方圆五公里,每天...
    莲苇阅读 8,101评论 0 1
  • 武当祭飞雪,春树裹银盔。慕名登金顶,吾心自芳菲。
    阿杜阿云阅读 271评论 1 7