Remove Duplicates from Sorted Array (Easy)

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

Analysis

= =.判断有序数组中不同的数的个数.简单题

My Solution

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