題目
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]
.
解題思路
移除數組中的重複元素,並返回新數組的長度。
這個題目應該算是簡單的題目。使用兩個變量就可以。具體的看代碼
代碼實現
class Solution {
public:
int removeDuplicates(int A[], int n) {
if(A==NULL || n<=0) return 0;
int start = 1;
int back = A[0];
for(int i=1;i<n;++i){
if(A[i] != back){
A[start++] = A[i];
back = A[i];
}
}
return start;
}
};
另外,我開通了微信公衆號--分享技術之美,我會不定期的分享一些我學習的東西.