Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
remove element. 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.
class Solution {
public:
int removeElement(int A[], int n, int elem) {
//scan from beginning,
// if find an instance of value, copy an element from tail, and shorten by one
// Note: the new element from tail can NOT be equal to value.
int tail = n-1;
for(int i=0; i<=tail; i++) {
if (A[i] == elem) {
//select one non-element number
while(tail >=i && A[tail] == elem)
tail --;
if (tail < i)
break;
A[i] = A[tail--];
}
}
return tail+1;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.