Sunday, November 11, 2012

Remove Element

Problem:
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.

Solution:
class Solution {
public:
    int removeElement(int A[], int n, int elem) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int i=0, count = 0, j = n-1;
        while (i < n && i <= j) {
            if (A[i] == elem) {
                swap(A[i], A[j--]);
                count++;
                continue;
            }
            i++;
        }
        return n - count;
    }
    void swap(int &a, int &b) {
        int temp;
        temp = a;
        a = b;
        b = temp;
    }
};

=============== Another smaller one =============
class Solution {
public:
    int removeElement(int A[], int n, int elem) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int iter = 0;
        for (int i = 0; i < n; i++) {
            if (A[i] != elem)
                A[iter++] = A[i];
        }
        return iter;
    }
};

No comments:

Post a Comment