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

tags: array two-pointers

简单题,用两个指针扫一遍数组,一个指向代表的原来数组,一个指向代表删除元素后的数组。

class Solution {
public:
    int removeDuplicates(int A[], int n) {
        int i,j;
        if(n==0)
          return 0;
        i = 1;
        j = 1;
        while(j<n){
            if(A[j]==A[j-1])
                j++;
            else{
                A[i++] = A[j++];
            }
        }
        return i;
    }
};

Untitled

 

 

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.