【LeetCode】Remove Duplicates from Sorted Array

来源:互联网 发布:陈道明 传承者 知乎 编辑:程序博客网 时间:2024/05/16 05:28

description:

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]

code : 本屌丝采用了两种方法都1A,第一种用了STL里面的算法,非常简单,第二种则是手动实现的

class Solution {public:    int removeDuplicates(int A[], int n) {        // Note: The Solution object is instantiated only once and is reused by each test case.                //int *end = unique(A,A+n);        //return end -A;                if(n == 0) return 0;        if(n == 1) return 1;                int i = 0,j = 1;        for(; j<n; j++)        {            if(A[j] != A[i])            {                A[++i] = A[j];            }        }        return i+1;    }};