java - 从数组中删除左侧重复项

标签 java arrays loops arraylist nested-loops

我正在尝试查找我的代码中的错误,我想知道您是否可以帮助我。我的任务是编写一个方法,将一个数组作为输入并返回这个数组而不留下重复项(最后一个数字保留)。我的代码在输入为(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 寻求帮助。如果您知道如何改进我的代码,请随意更改您想要的一切。提前致谢!

最佳答案

HashSet可以这样做,因为你不能将重复元素放入 HashSet ,您需要做的就是将数组放入 HashSet .

List<Integer> arr2 = new ArrayList<>(new HashSet<>(arr));

关于java - 从数组中删除左侧重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63458798/

相关文章:

java - 在哪里放置内部类?

php - PHP while 循环中的 SQL SELECT

java - 关于sizeof的问题。我想反转数字中的位

java - 拒绝超出 DoubleProperty 范围的更改

java - Hibernate 无法与 Sql Server 2008 一起使用

javascript - 向数组中的特定对象添加属性

c++ - 如何避免字符数组的叠加?

python - 从 python 数组中获取高阶字节

c++ - 为什么我的 if 语句在应该评估为 false 时却没有评估为 false?

java - 连接 3 个或更多表会产生重复的元组