首页 > 代码库 > leetcode 题解:Remove Duplicates from Sorted Array(已排序数组去重)

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

说明:

      1)无

实现:

 1 class Solution { 2 public: 3     int removeDuplicates(int A[], int n) { 4         if(n==0) 5         return 0; 6         int B[n],k=0; 7         for(int i=0;i<n;i++) 8            B[i]=0; 9            B[0]=A[0];10         for(int i=1;i<n;i++)11            {12                if(B[k]!=A[i])13                   B[++k]=A[i];14            }15            for(int i=0;i<=k;i++)16                A[i]=B[i];17            return k+1;18         19     }20 };