leetcode_question_26 Remove Duplicates from Sorted Array

来源:互联网 发布:美工助理 编辑:程序博客网 时间:2024/06/11 18:45

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

int removeDuplicates(int A[], int n) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        if(n < 1) return 0;        int index = 0;        int pre = 1;        while(pre < n){            if(A[pre] == A[index]) pre++;            else{                if(pre - index == 1){pre++; index++;}                else A[++index] = A[pre++];            }                    }        return index + 1;    }


原创粉丝点击