java - 在向列表中添加另一个数字之前,如何检查列表中是否有重复项?

标签 java loops arraylist

所以我有一项任务要做,其中涉及不使用集合或映射。任务是创建两个排序整数列表的交集列表,并且不向该列表添加任何重复项。我已经弄清楚了第一部分,但问题是我不知道如何检查要添加的整数是否不在列表中?

我猜有某种循环?

     public ArrayList<Integer> Intersection(ArrayList<Integer> A,   ArrayList<Integer> B) {
    ArrayList<Integer> result = new ArrayList<Integer>();

    int i = 0;
    int j = 0;

    while (i != A.size() && j != B.size()) {
        if (A.get(i) < B.get(j)) {
            i ++;
        } 

        else if (A.get(i) > B.get(j)) {
            j ++;
        }

        else {
            result.add(A.get(i));
            i ++; j++;
        }

    }


    return result;
  }
 }

因此,通过上面的代码,我得到了交集,但它有重复项,例如来自

列表 A [2, 2, 2, 3] 和

列表 B [2,2,3,4]

当预期结果是[2, 3]时,我得到的结果是[2, 2, 3]

最佳答案

  • 始终针对接口(interface)编写代码
  • 只需添加一张支票。检查下面代码中的注释

    public static List<Integer> intersection(List<Integer> A, List<Integer> B) {
        List<Integer> result = new ArrayList<Integer>();
    
        int i = 0;
        int j = 0;
    
        while (i != A.size() && j != B.size()) {
            if (A.get(i) < B.get(j)) {
                i++;
            }
    
            else if (A.get(i) > B.get(j)) {
                j++;
            }
    
            else {
                // If already contains item dont add again
                if (!result.contains(A.get(i))) {
                    result.add(A.get(i));
                }
                i++;
                j++;
            }
    
        }
    
        return result;
    }
    
    public static void main(String[] args) {
        List<Integer> r = intersection(Arrays.asList(2, 2, 2, 3), Arrays.asList(2, 2, 3, 4));
        System.out.println(r);
    }
    

关于java - 在向列表中添加另一个数字之前,如何检查列表中是否有重复项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57874878/

相关文章:

python - 在Python中通过REGEX查找项目的索引

java - 循环/数组 (Java)

java - Android - 从后台线程返回 ArrayList 到 Activity

java - java中的虚拟磁盘空间预留

填充 ListView 时出现 JavaFx NullPointer 异常

java - 简单的 Servlet 在 Eclipse 中不起作用,构建文件夹为空,抛出 ClassNotFoundException

java - 将 ArrayList 拆分为给定数量的子 ArrayList

java - PhP 与 Java 哪个最适合中型到企业级 Web 应用程序?

javascript - 获取多维数组的最大值

java - 在承包商中初始化未知大小的ArrayList - Java