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 nums = [1,1,2]
,
Your function should return length = 2
, with the first two elements of nums being 1
and 2
respectively. It doesn't matter what you leave beyond the new length.
Subscribe to see which companies asked this question.
class Solution {
public:
int removeDuplicates(vector<int>& A) {
int count = 0;
int n=A.size();
for(int i = 1; i < n; i++){
if(A[i] == A[i-1]) count++;
else A[i-count] = A[i];
}
return n-count;
}
};
编写过程出现较大失误,在最初对题目理解错误,忽略了数组已排序问题,然后废了很大周章。
然后再次审题比较轻松的完成,算法也选择了比较简单的。