首页 > 编程语言 > 详细

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

时间:2017-02-25 22:52:30      阅读:229      评论:0      收藏:0      [点我收藏+]

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;
}

测试通过

 

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

原文:http://www.cnblogs.com/tao-alex/p/6443032.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!