问题描述:
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]
.
解决原理:
(若输入数组无序,则先对数组进行排序,则相同值相邻)
两个游标len,i
0~len是元素不重复的子数组,即len是目标子数组的最后一个元素的索引
游标i遍历数组
若A[i]!=A[len],则为目标子数组增添一个元素
代码:
1 class Solution { 2 public: 3 int removeDuplicates(int A[], int n) { 4 int len = 0; 5 if(n == 0) return 0; 6 //sort(A,A+n); 7 for(int i = 1; i < n; i++){ 8 if(A[i] != A[len]){ 9 len++; 10 A[len] = A[i]; 11 } 12 } 13 return len+1; 14 } 15 };