原题:
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]
.
和处理指针时的想法类似,不过我多开了一个数组空间,这样A数组就可以用来记录没有新的数组返回值了。
代码如下:
class Solution {
public:
int removeDuplicates(int A[], int n) {
int tmp = A[0];
int *a = new int[n];
int j, i;
for(i = 0; i<n; i++) a[i] = A[i];
for(i = 1, j = 1; i<n && j<n; i++) {
if( a[i]!=tmp){
A[j] = a[i];
tmp = a[i];
j++;
}
}
return j;
}
};
卡在了最后一个情况上,但是,数组这种东西怎么会出现空阿?完全无法理解这个呀,求指点debug!
=============================================================================================================================
男喷油指点后加了一句“if(n==0) return 0;”判断数组长度,然后AC了=。=