题目链接: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.

这道题的要求是在一个数组中删除指定元素,并返回新数组的长度。其中新数组的元素顺序可以改变。

这道题的思路就是采用两个指针l和r,l记录不包含指定元素的下一位置(即新数组当前长度),r从头开始遍历数组,如果r位置的数字等于指定数字,不予处理;如果r位置的数字不等于指定数字,需要把r处数字放到l的位置,并使l加1。

时间复杂度:O(n)

空间复杂度:O(1)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution
{
public:
    int removeElement(int A[], int n, int elem)
    {
        if(n == 0)
            return 0;
        
        int l = 0;
        for(int r = 0; r < n; ++ r)
            if(A[r] != elem)
                A[l ++] = A[r];
        return l;
    }
};