Question: Given an array and a value, how to implement a function to 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.
Two pointers are defined to solve this problem: The first pointer (denoted as p1) moves forward until it reaches a number equal to the target value, which is initialized to the beginning of array. The other (denoted as p2) moves backward until it reaches a number not equal to the target value, which is initialized to the end of array. Two numbers pointed by p1 and p2 are swapped. We repeat the moving and swapping operations until all target numbers are scanned.
int removeElement(int A[], int n, int elem)
Two pointers are defined to solve this problem: The first pointer (denoted as p1) moves forward until it reaches a number equal to the target value, which is initialized to the beginning of array. The other (denoted as p2) moves backward until it reaches a number not equal to the target value, which is initialized to the end of array. Two numbers pointed by p1 and p2 are swapped. We repeat the moving and swapping operations until all target numbers are scanned.
unsigned int Remove(int* numbers, unsigned int length, int n)
{
if(numbers == NULL || length < 1)
return 0;
int* p1 = numbers;
int* p2 = numbers + length - 1;
while(p1 < p2)
{
while(*p1 != n && (p1 - numbers) < length)
++p1;
while(*p2 == n && (p2 - numbers) > 0)
--p2;
if(p1 < p2)
{
*p1 = *p2;
*p2 = n;
}
}
return p1 - numbers;
}
http://comproguide.blogspot.com/2014/03/removing-all-instances-of-number-in.htmlint removeElement(int A[], int n, int elem)
Read full article from Coding Interview Questions: No. 32 - Remove Numbers in Array{int res = 0;for( int i = 0; i < n ; i++ ){if( A[i] != elem )A[res++] = A[i];}return res;}