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.
*/The order of elements can be changed. It doesn't matter what you leave beyond the new length.
class Solution {
public:
void swap(int A[], int i, int j){
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
int removeElement(int A[], int n, int elem) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(n<=0) return 0;
int i = 0;
while(i<n && A[i]!=elem){
i++;
}
if(i==n) return n;
int j = n-1;
while(j>=0 && A[j]==elem){
j--;
}
if(j==-1) return 0;
if(i>=j) return i;
int pos = 0;
while(i<j){
swap(A, i, j);
pos = i;
i++;
j--;
while(i<n && A[i]!=elem){
i++;
}
while(j>=0 && A[j]==elem){
j--;
}
}
while(pos<n && A[pos]!=elem){
pos++;
}
return pos;
}
};
No comments:
Post a Comment