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].

要求:不准额外空间,且时间O(n)

思路:index很重要,是去重复后的新数组的长度,默认值1。对一个已排序的有重复的数组,重复数字肯定是连续的

如1,1,1,1,2,2,2,2,5,5,5,我们需要做的就是把连续的2序列的第一个放到前面去(第一个数字之后,更新A[index]),把连续的5序列的第一个放到前面去,那么条件判断就是看什么时候可以找到前一个值和当前值不相等,那么我我们就要做处理。

代码:

class Solution {
public:
    int removeDuplicates(int A[],int n){
        int index=1;
        if(!n) return 0;
        for (int i=1;i<n;++i)
        {
            if(A[i]!=A[i-1]){
                A[index]=A[i];
                index++;
            }
        }
        return index;
    }
};
原文地址:https://www.cnblogs.com/fightformylife/p/4073285.html