This is a facebook intern interview question.
Problem:
Given an array and a value, remove all instances of that value in place and return the new length.
Solution:
class Solution {
public:
int removeElement(int array[], int len, int elem) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int start = 0, end = len - 1;
if (len == 0)
return 0;
while (start <= end) {
if (array[start] == elem) {
swap(array[start], array[end]);
end--;
} else {
start++;
}
}
return start;
}
void swap(int &first, int &second) {
int temp;
temp = first;
first = second;
second = temp;
}
};
No comments:
Post a Comment