LeetCode | Remove Element(删除指定元素)


Given an array and a value, remove all instances of that value in place and return the new length.

The order of elements can be changed. It doesn't matter what you leave beyond the new length.

删除数组中制定的元素,返回新的长度


题目解析

这道题和上一道题目很类似,也是遇到不合法的数据用后面的数据替换,不过这里的j不是从前往后遍历, 而是从后向前遍历,找到第一个不是关键字的数据放置到arr[i]的位置,然后i+1继续遍历。注意一些细节,比如输入的参数不合法(空指针,长度为零等情况),这道题目就不难了。

另:

也可以跟上一题一样,i和j都是从前向后遍历,当arr[j]的值和key的值不相等就对arr[i]进行赋值。

#include <stdio.h>
#include <stdlib.h>

int RemoveElement(int arr[],int len,int key);

int main()
{
    int n,key;
    int arr[20];

    while(scanf("%d %d",&n,&key) != EOF){
        for(int i = 0;i < n;++i)
            scanf("%d",&arr[i]);
        int len = RemoveElement(arr,n,key);
        printf("len = %d\n",len);
        for(int i = 0;i < len;++i){
            printf("%d ",arr[i]);
        }
        putchar('\n');
    }

    return 0;
}

int RemoveElement(int arr[],int len,int key)
{
    int i = 0,j = len-1;

    if(arr == NULL || len <=0)
        return 0;

    while(i <= j){
        if(arr[i] == key){
            while(i<=j){
                if(arr[j] != key)
                    break;
                --j;
            }
            if(i>j) //当最后的数据全部都是要删除的关键字的时候,会产生这样的情况
                break;
            arr[i] = arr[j];    //将后面的数据放置到要删除的数据的位置
            --j;
        }
        ++i;
    }
    //最后返回的i的位置,不是合法的数据,从0--> i-1位置才是我们要求解的
    return i;   //这时的返回值表示长度
}




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值