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

 解题思路:

依次从array中寻找新的元素,顺序放到array前端,然后跳过重复元素,寻找新的元素,直到末尾。

class Solution {
public:
    int removeDuplicates(int A[], int n) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        if(n <= 1)
            return n;
        
        int loc = 0, val_loc = 0;
        while(loc < n)
        {
            A[val_loc] = A[loc];
            val_loc++;
            
            int next = n;
            for(int i = loc + 1;i < n;i++)
            {
                if(A[i] != A[loc])
                {
                    next = i;
                    break;
                }
            }
            loc = next;
        }
        return val_loc;
    }
};
posted @ 2013-11-10 11:38  xchangcheng  阅读(122)  评论(0编辑  收藏  举报