我试图在我的代码中找出错误,我想知道你是否能帮我。我的任务是编写一个将数组作为输入的方法,并返回这个数组而不留下重复项(最后一个数字保持不变)。如果输入是( 1,2,1,2,1,2, 3 ),它返回(1,1,2,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;
    
       }
     }我试着自己完成这个任务,所以直到现在我才用谷歌来寻求帮助。如果您知道如何改进我的代码,可以随意更改任何您想要的内容。提前谢谢你!
发布于 2020-08-17 21:42:20
一个简单的方法就是
LinkedHashSet中,以便只保留唯一的数字,并保留每个唯一数字的最后一个条目。List中创建一个LinkedHashSet。List逆转Collections#reverse。
导入java.util.ArrayList;导入java.util.Collections;导入java.util.LinkedHashSet;导入java.util.List;导入java.util.Set;公共类Main { public静态void (String[] args) { Set =新LinkedHashSet<>();int[] arr ={ 7,7,4,5,7,2,7 };//将数组的编号反向添加到LinkedHashSet中,以便删除//重复项,并保留每个唯一数字的最后一个条目。对于(int i= arr.length - 1;i- >= 0;i-){ set.add(arri);} //从LinkedHashSet列表中创建一个列表=新的ArrayList<>(set);//反转列表Collections.reverse(列表);//显示结果System.out.println(列表);}}输出:
[4, 5, 2, 7]发布于 2020-08-17 21:31:16
发布于 2020-08-17 21:29:42
您可以创建第二个列表,迭代输入列表,并检查输入列表的每个元素是否包含第二个列表。如果没有,将其添加到第二个列表中。这通过了您在原始文章中提到的测试用例:
import java.util.*;
public class MyClass {
    public static void main(String args[]) {
      List<Integer> test = new ArrayList<>();
      List<Integer> noduplicates = new ArrayList<>();
      test.add(1);
      test.add(2);
      test.add(1);
      test.add(2);
      test.add(1);
      test.add(2);
      test.add(3);
      
      for (Integer i : test) {
          if (!noduplicates.contains(i)) {
              noduplicates.add(i);
          }
      }
      System.out.println(noduplicates);
    }
}https://stackoverflow.com/questions/63458798
复制相似问题