arraylist<integer> list = new arraylist<integer>();
// 去掉数组中重复的元素
public int removetheagain01(int[] array) {
if (array == null || array.length == 0) {
return 0;
} else if (array.length == 1) {
return 1;
} else {
int i = 0;
int n = array.length - 1;
while (i <= n) {
if (i == n) {
list.add(array[i]);
i++;
} else {
int j = i + 1;
if (array[i] == array[j]) {
while (j <= n && array[i] == array[j]) {
j++;
}
}
list.add(array[i]);
i = j;
}
}
for (int k = 0; k < list.size(); k++) {
array[k] = list.get(k);
}
return list.size();
}
}
public int removetheagain02(int[] array) {
if (array == null || array.length == 0) {
return 0;
} else if (array.length == 1) {
return 1;
} else {
int end = array.length - 1;
for (int i = 0; i <= end; i++) {
if (i < end) {
int j = i + 1;
if (array[i] == array[j]) {
while (j <= end && array[i] == array[j]) {
j++;
}
}
system.arraycopy(array, j, array, i + 1, end - j + 1);
end -= j - i - 1;
}
}
return end + 1;
}
}
三:借助临时变量解决问题
时间复杂度o(n),空间复杂度o(1)
public int removetheagain03(int[] array) {
if (array == null || array.length == 0) {
return 0;
} else if (array.length == 1) {
return 1;
} else {
int temp = array[0];
int len = 1;
for (int i = 1; i < array.length; i++) {
if (temp == array[i]) {
continue;
} else {
temp = array[i];
array[len] = array[i];
len++;
}
}
return len;
}
}