LeetCode_Easy心得:27. Remove Element(C语言)

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.

/** 题目分析:本题与#26的 Remove Duplicates from Sorted Array 很相似,#26是只能在原输入数组内删除重复数,同样,本题也只能在原数组内删除指定数字。最后两题都是返回的 “新数组” 的长度。 */

Example:

Given input array nums = [3, 2, 2, 3], val = 3;

return 2;


/** 代码思路:思路和#26相差不大,同样需要两个数组下标,即 length下标和 i下标,其中 i下标是遍历整个数组,而 length下标表示的是“新”数组。在 i下标遍历数组过程中,若遇到目标数,下标 i向后移动, length不进行操作;若遇到的数不是目标数,则将 i下标数赋给 length下标数,接着 i与 length向后移动,直至 i将数组完整遍历。这一题和#26不相同的是,#26的 length是从第二个数字(即 length=1)开始操作的,而这一题需要从 length=0开始,因为#26的 0下标数字肯定保留(因为 0下标前面没有数字也就不是重复了),而这一题 0下标数字是否与目标数相同,需要进行判断,因此从 length=0开始操作。 */

Example:

nums[i] = {1, 2, 1, 3, 1, 3, 2, 2, 2};

val = 2;

then, nums[length] = {1, 1, 3, 1, 3, 3, 2, 2, 2};        //因为length只能到5, 5下标后的数间接过滤了;

return 5;

/** 在上面Example中,nums[length]数组中的 3 情况比较特殊,因为 length=5处在逻辑上应该是没有数字的,但是因为是在数组内部操作,所以说 length=5处数字被原数组赋值了。 */



int removeElement(int nums[], int numsSize, int val) {
    int i, len=0;           // i下标和 length下标;
    
    if(numsSize <= 0)
        return numsSize;    //如果数组原数组长度非正常值,直接返回;
    
    for(i=0; i<numsSize; i++){
        if(nums[i] != val){
            nums[len] = nums[i];    //如果i处数与目标数不相等,则将i位置数赋给length位置;
            len ++;
        }
    }
    
    return len;             //在i遍历过程中,length已经在判断语句中自增1,因此直接返回length;;
}

// LeetCode运行时间:3ms;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值