【发布时间】:2020-12-07 01:24:38
【问题描述】:
我正在尝试找出我的代码中的错误,不知道您是否可以帮助我。我的任务是编写一个方法,该方法将数组作为输入并返回该数组而没有左重复项(最后一个数字保留)。如果输入是(1,2,1,2,1,2,3),我的代码不起作用它返回(1,1,2,3)而不是1,2,3。这是代码
public static int [] solve(int [] arr){
boolean check=false;
ArrayList<Integer> test = new ArrayList<>(); // idk how to compete this task without ArrayList
for (int i = 0; i < arr.length; i++) { // Here i pass my array to ArrayList
test.add(arr[i]);
}
while(check==false) {
for (int i = 0; i < test.size(); i++) {
for (int j = i + 1; j < test.size(); j++) { // Somewhere here must be my mistake that i can't find
check=true;
if (test.get(i) == test.get(j)) {
test.remove(i);
check=false;
}
}
}
}
// i created second array to return array without duplcates.
int arr2[];
arr2=new int[test.size()];
for(int i=0;i<arr2.length;i++){
arr2[i]=test.get(i);
}
return arr2;
}
}
我尝试自己完成这项任务,所以直到现在我才使用 Google 寻求帮助。如果您知道如何改进我的代码,请随时更改您想要的所有内容。提前谢谢!
【问题讨论】:
-
您只想返回唯一值?
-
我想删除最后一个之前的所有重复项。例如 - 7,7,4,5,7,2,7(输入)和 4,5,2,7(输出)。如您所见,最后 '7' 停留
-
嗯,它只是返回给定数组中的唯一元素,对吧?任何最后一个重复元素的位置意味着只有唯一元素。或者您是否只想删除最后一个重复元素的重复元素,而在最后一个重复元素之前保留其他重复元素不变。是哪一个?
-
是的,我想你是对的
-
我说了2个选项。如果您说我的第二个解释是正确的,那么您显示的输出将按预期工作。或者对于我的第一个选项,如果您只想要独特的元素,只需使用 HashSet
标签: java arrays loops arraylist nested-loops