LeetCode: Remove Duplicates from Sorted Array

来源:互联网 发布:网络推广转化率 编辑:程序博客网 时间:2024/04/29 06:54

Given a sorted array, remove the duplicates in place such that each element appear onlyonce 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].



class Solution {public:    int removeDuplicates(int A[], int n) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        if(n <= 1){return n;}        int pos = 0;        for(int i = 0; i< n; ++i){            while(i < n- 1 && A[i] == A[i +1]){                i++;            }            A[pos++] = A[i];        }        return pos;    }};


原创粉丝点击