【LeetCode】26. Remove Duplicates from Sorted Array

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

 

两个指针,一个ind指向新数组的新位置,一个i遍历原数组,in-place实现。

使用last记录上一个遍历到的数字。

如果A[i]与last相等,则跳过。如果A[i]是一个新数字,则赋给A[ind],并且ind前进一位。

class Solution {
public:
    int removeDuplicates(int A[], int n) {
        if(n == 0)
            return 0;
        int ind = 1;
        int last = A[0];
        for(int i = 1; i < n; i ++)
        {
            if(A[i] != last)
            {
                A[ind ++] = A[i];
                last = A[i];
            }
        }
        return ind;
    }
};

posted @ 2014-05-24 23:20  陆草纯  阅读(202)  评论(0编辑  收藏  举报