题目链接:Remove Duplicates from Sorted Array

Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

For example,

Given input array A = [1,1,2],

Your function should return length = 2, and A is now [1,2].

这道题的要求是在有序数组中删除重复元素,使每个数字出现且只出现1次,并返回数组的新的长度。要求:不允许申请额外空间,即要求恒定的空间复杂度。

这道题的思路就是采用两个指针l和r,l记录不重复元素的位置,r从l的下一个开始遍历数组,如果r位置的数字等于l位置的数字,说明该数字重复出现,不予处理;如果r位置的数字不等于l位置的数字,说明该数字没有重复,需要放到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 removeDuplicates(int A[], int n)
    {
        if(n == 0)
            return 0;
        
        int l = 0;
        for(int r = 1; r < n; ++ r)
            if(A[r] != A[l])
                A[++ l] = A[r];
        return l + 1;
    }
};