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; }
测试经过测试