描述
Given an array and a value, remove all instances of that value in place and return the new length.
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.
#include<iostream>
using namespace std;
int RemoveElement(int a[], int n,int value)
{
if (a == NULL || n <= 0)
return 0;
int i = 0;
int k = 0;
for (; i < n; )
{
if (a[i] == value)
{
i++;
}
else
{
a[k] = a[i];
k++;
i++;
}
}
return k;
}
int main()
{
const int n = 10;
int a[n] = { 1, 2, 4, 4, 4, 4, 5, 6, 6, 6 };
int value = 6;
int k = RemoveElement(a, n, value);
for (int i = 0; i < k; i++)
cout << a[i] << " ";
cout << endl;
}