/**
*
* @author VK
* @Date 2016-12-19 10:48
* @Decribe 题目:给定一个整数型一维数组,去除重复元素形成新数组,
* 并返回新数组长度。不额外分配数组空间
*
*/
public class Demo {
public static void main(String[] args) {
int[] src = { 0, 1, 1, 1, 1, 2, 3, 4, 4, 5, 6, 7, 8, 8, 9, 9, 9 };
print(src,src.length);
System.out.println("\n========== after calculate ==========\n");
int len = calculate(src);
print(src,len);
}
public static int calculate(int[] src) {
if (src == null || src.length == 0)
return 0;
int ret = 0;
int count = 0;
int index = 1;// 新数组的下标索引
int tmp = src[0];
for (int i = 1; i < src.length; i++) {
// 1.前后元素若相同 count++
if (tmp == src[i]) {
count++;
} else {// 2.若不相同,count>0表示前面有重复值,需要进行去重位移
tmp = src[i];
if (count > 0) {
src[index] = src[i];
}
index++;
}
}
ret = index;
System.out.println("The number of removed elements =" + count);// 打印移除重复次数
return ret;
}
public static void print(int[] src,int len){
StringBuffer mBuffer = new StringBuffer();
mBuffer.append("len=");
mBuffer.append(len);
mBuffer.append('\n');
for (int i = 0; i < len; i++) {
mBuffer.append(src[i]);
mBuffer.append('\0');
}
System.out.println(mBuffer.toString());
}
}
计算结果: