[leetcode_27]Remove Element

This problem was tricky! You really need to understand English well and read the problem carefully.

At first I thought I just needed to return the length after deletion. But that’s not all – you also need to make sure the first length elements of array A are valid.

Got WA at first, then Accepted on the next try.

Here is the code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
    int removeElement(int A[], int n, int elem) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        int length = 0;
        int *B = new int[n];
        for(int i = 0;i < n;i++)
        {
            if(A[i] != elem)
            {
                B[length++] = A[i];
            }
        }
        for(int i = 0;i < length;i++)
        {
            A[i] = B[i];
        }
        return length;
    }
};

A better approach would be to use two pointers and swap elements with the end of the array.