sundeepblue
4/15/2014 - 3:43 PM

In place, move the duplicates in an array to the end.

In place, move the duplicates in an array to the end.

// idea: always compare current item with all previous items. If current appears before, 
// it means the current is a duplicate. Then swap it with the tail.

void move_duplicates_to_end(vector<int> &A) {
    if(A.empty()) return;
    int i = 0, tail = A.size()-1;
    while(i <= tail) {
        bool has_duplicate = false;
        for(int k=0; k<i; k++) {
            if(A[k] == A[i]) {
                has_duplicate = true;
                break;
            }
        }
        if(has_duplicate == false) i++;
        else {
            swap(A[i], A[tail]);
            tail--;
        }
    }
}