Java =如何在int数组中删除重复而不使用集合或方法,如Arrays.copyOf()?


public static int[] removeSameNumber(int[] input) {

removeSamenumber() takes numbers (int) to array and returns new array with deleted duplicates.

new int[] {2, 2} ==== new int[] {2}

new int[] {1, 2, 1, 3, 2} ==== new int[] {1, 2, 3}

不能使用List、Set或其他动态集合。你只需要处理数组。

已存在的函数,如数组。不能使用copyOf ()

我尝试了很多不同的方法,但都不起作用

我是初学者,你的帮助将非常帮助我:)

如果您想在没有库方法的情况下对数组进行重复数据删除,您可以这样做:

public static void main(String[] args) {
int[] source = new int[] {1, 2, 1, 3, 2, 1, 4, 3, 2, 1, 11};
int maxElement = 0;
int sizeWithoutDouble = source.length;
//get max int from source array, for getting temp array size
for (int i = 0; i < source.length; i ++){
maxElement = Math.max(maxElement, source[i]);
}
int temp[] = new int[maxElement + 1];
//put in temp array uniuque int and decrement total int count
for (int i = 0; i < source.length; i ++){
if (temp[source[i]] == 0){
temp[source[i]] = source[i];
}else {
sizeWithoutDouble--;
}
}
//declare result array with size uniuque int
int result[] = new int[sizeWithoutDouble];
int currentRes = 0;
//filling result array
for (int i = 0; i < temp.length; i ++){
if (temp[i] != 0){
result[currentRes++] = temp[i];
}
}   
}

输出:

[1, 2, 3, 4, 11]
int[] temp = new int[inputs.length];
int nUnique = 0;
for(int i=0;i<inputs.length;i++) {
boolean dup = false;
for(int j=i+1;j<inputs.length;j++) {
if(inputs[i]==inputs[j]) {
dup = true;
break;
}
}

if(!dup) {
temp[nUnique] = inputs[i];
nUnique++;
}
}
int[] result = new int[nUnique];
for(int i=0;i<nUnique;i++) {
result[i] = temp[i];
//System.out.println(result[i]);
}
return result;

最新更新