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

//用两个指针,pCur保存当前数组位置,pWork为遍历工作指针。

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

 

posted on 2017-03-08 08:18  123_123  阅读(67)  评论(0编辑  收藏  举报