code第一部分数组:第十题:移除数组中目标元素

本文介绍了一种从数组中删除特定值的有效方法,并提供了两种实现方式:一种是使用简单的索引移动法,另一种是利用STL库进行操作。通过示例代码展示了如何将不等于目标值的元素前移并返回新的有效长度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

code第一部分数组:第十题:移除数组中目标元素

 

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

解决方法1,很简单的题
直接用一个索引,把数组元素往前移动;
解决方法2 使用STL

#include <iostream>
using namespace std;

int removeElem(int a[],int n,int target)
{
    int index=0;
    int i;
    for ( i = 0; i < n; i++)
    {
        if (a[i]!=target)
        {
            a[index]=a[i];
            index++;
        }
    }
    return index;
}

int removeElem2(int A[], int n, int elem)
{
    return distance(A, remove(A, A+n, elem));
}

int main()
{
    int a[7]={1,1,2,3,5,6,6};
    int ans=removeElem(a,7,3);
    cout<<"ans is "<<ans<<endl;
    return 0;
}

测试通过

 

转载于:https://www.cnblogs.com/tao-alex/p/6443032.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值