code第一部分數組:第十題:移除數組中目標元素

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 lengthios

解決方法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;
}

測試經過測試

相關文章
相關標籤/搜索