問題描述:
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]
.
就是去掉數組中重複的數字,只保留一個,返回處理後數組中的元素個數,要求不能再設置一個數組!
解題思路:
很簡單,不多說!算法複雜度O(n)!
class Solution {
public:
int removeDuplicates(int A[], int n) {
if(n == 0)
return 0;
int start = 0;
int key = A[0];
int i = 0;
while(i < n)
{
if (A[i] != key)
{
A[start++] = key;
key = A[i];
}
i++;
}
A[start++] = key;
return start;
}
};