You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java新手求助:比较两数组生成无重复公共元素数组

解决数组公共元素去重的问题(新手友好版)

嘿,作为Java新手能自己尝试写逻辑已经很棒啦!咱们先看看你当前代码里的核心问题:你没有正确判断元素是否已经被加入common数组,而且循环的逻辑有点混乱,导致重复元素被多次添加。

我给你改了一个用纯基础循环+判断的版本,完全不用任何进阶工具,保证你能看懂:

public static void main (String[] args) { 
    int[] a1 = {3, 8, 5, 6, 5, 8, 9, 2}; 
    int[] a2 = {5, 15, 4, 6, 7, 3, 9, 11, 9, 3, 12, 13, 14, 9, 5, 3, 13}; 
    int[] common = new int[a1.length]; 
    System.out.println("Exercise 3: "); 
    findCommon(a1,a2,common); 
} 

public static void findCommon(int[] a1, int[]a2, int[] common) { 
    // 用这个变量记录common数组里已经放了多少个去重后的元素
    int currentIndex = 0;

    // 遍历a1里的每个元素
    for (int i = 0; i < a1.length; i++) {
        int currentNum = a1[i];
        boolean isInCommon = false;
        boolean isInA2 = false;

        // 第一步:检查这个元素是不是已经在common里了(去重)
        for (int k = 0; k < currentIndex; k++) {
            if (common[k] == currentNum) {
                isInCommon = true;
                break; // 已经找到重复,不用继续查了
            }
        }
        if (isInCommon) {
            continue; // 已经在common里了,跳过这个元素
        }

        // 第二步:检查这个元素是不是在a2里存在
        for (int j = 0; j < a2.length; j++) {
            if (a2[j] == currentNum) {
                isInA2 = true;
                break; // 找到存在,不用继续查了
            }
        }

        // 如果既不在common里,又在a2里,就加入common
        if (isInA2) {
            common[currentIndex] = currentNum;
            currentIndex++;
        }
    }

    // 输出结果
    for (int elements : common) {
        System.out.print(elements + " ");
    }
}

为什么这样改?我给你拆解每一步:

  • 用currentIndex来控制common数组的插入位置,避免用a1的下标i直接赋值,这样能保证去重后的元素依次往前放
  • 先检查元素是否已经在common里(只查已经插入的前currentIndex个元素),避免重复添加
  • 再检查元素是否在a2里存在,只有两个条件都满足才加入common
  • 最后common数组剩下的位置本来就是默认的0,刚好符合你的期望输出

运行这个代码后,输出就是你想要的:3 5 6 9 0 0 0 0

内容的提问来源于stack exchange,提问作者user9751491

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:44:38