大家帮忙看看--数组排序后删除重复元素的问题!
以下是我写的代码,不过这个变量number总是得不出我想要的值,请高手执教一下
public class SortArray {
public static int[] sortAndOptimizeArray(int[] array) {
Sort.sortIntegerArray(array);
int noOfRepeats=0;
int number=0;
for(int i=0;i <array.length;i++) {
boolean ok=false;
for(int j=i+1;j <array.length;j++) {
if(array[i] == array[j]) {
ok=true;
noOfRepeats++;
number++;
} else break;
}
if(ok == true) {
for(int k=i;k <array.length;k++) {
if((k+noOfRepeats) < array.length) array[k] = array[k+noOfRepeats];
}
ok=false;
noOfRepeats=0;
}
}
int len=array.length - number;
int[] newArray=new int[len];
for(int i=0;i <newArray.length;i++) {
newArray[i]=array[i];
}
return newArray;
}
public static void main(String[] args) {
int[] test = {3, 4, 3, 13, -5, 4};
test = sortAndOptimizeArray(test);
for(int i=0;i < test.length;i++ ) {
System.out.print(test[i] + ", ");
}
}
}
------解决方案--------------------public class SortArray {
public static int[] sortAndOptimizeArray(int[] array) {
// Sort.sortIntegerArray(array);
int number = 0;
for (int i = 0; i < array.length-number; i++) {
for (int j = i + 1; j < array.length-number; j++) {
if (array[i] == array[j]) {
for (int k = j; k < array.length-number; k++) {
if ((k + 1) < array.length-number)
array[k] = array[k + 1];
}
number++;
j--;
}
}
}
int len = array.length - number;
int[] newArray = new int[len];
for (int i = 0; i < newArray.length; i++) {
newArray[i] = array[i];
}
return newArray;
}
public static void main(String[] args) {
int[] test = { 3, 4, 3, 13, -5, 4 };
test = sortAndOptimizeArray(test);
for (int i = 0; i < test.length; i++) {
System.out.print(test[i] + ", ");
}
}
}