题目:
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]
.
思路:
方法1:利用一个Hash表或者BitMap记录重复的数值,遍历数组时遇到重复时跳过。 方法2:题目中提到了in place,所以最好不需要利用额外的空间。利用快慢索引可以完成比较与位置置换。
代码:
方法1:
class bitmap {
public: bitmap(int n);~bitmap();
void set(int k);
bool val(int k);
private: int len;
unsigned int * map;
unsigned int * reversemap;
bool zero;
};
bitmap::bitmap(int n) {
len = n / 32 + 1;
map = new unsigned int[len];
reversemap = new unsigned int[len];
for (int i = 0; i < len; i++) {
map[i] = 0;
reversemap[i] = 0;
zero = false;
}
}
void bitmap::set(int k) {
bool reverse = true;
if (k == 0) {
zero = true;
} else if (k < 0) {
reverse = false;
k = -k;
}
int a = k / 32;
int b = k % 32;
if (a >= len) {
return;
} else {
if (reverse) {
int tmp = reversemap[a] / pow(2, b);
if (tmp % 2 == 0) {
reversemap[a] += pow(2, b);
}
} else {
int tmp = map[a] / pow(2, b);
if (tmp % 2 == 0) {
map[a] += pow(2, b);
}
}
}
}
bool bitmap::val(int k) {
bool reverse = true;
if (k == 0) {
return zero;
} else if (k < 0) {
reverse = false;
k = -k;
}
int a = k / 32;
int b = k % 32;
if (a >= len) {
return false;
} else {
if (reverse) {
int tmp = reversemap[a] / pow(2, b);
if (tmp % 2 == 1) {
return true;
} else {
return false;
}
} else {
int tmp = map[a] / pow(2, b);
if (tmp % 2 == 1) {
return true;
} else {
return false;
}
}
}
}
class Solution {
public:
int removeDuplicates(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
bitmap* bm = new bitmap(32767);
int count = 0;
int skip = 0;
for(int i = 0; i< n; i++)
{
if(bm->val(A[i]))
{
skip++;
count++;
}
else
{
bm->set(A[i]);
A[i-skip] = A[i];
}
}
return n-count;
}
};
方法2:
class Solution {
public:
int removeDuplicates(int A[], int n) {
if(n == 0){
return 0;
}
int slow = 0;
int fast = 1;
while(fast < n){
if(A[slow] != A[fast]){
A[++slow] = A[fast];
}
fast++;
}
return slow + 1;
}
};