Skip to content

Instantly share code, notes, and snippets.

@xiren-wang
Created September 1, 2014 06:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xiren-wang/5902e1cb76cd418b2572 to your computer and use it in GitHub Desktop.
Save xiren-wang/5902e1cb76cd418b2572 to your computer and use it in GitHub Desktop.
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