Created
September 1, 2014 06:40
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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