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

CodeWars Array.diff题目Java代码无法通过平台测试求助

问题:CodeWars Array.diff 挑战代码排查

挑战要求

本次 kata 的目标是实现一个差值函数,从一个列表中减去另一个列表并返回结果。
需要移除列表a中所有在列表b中出现的值,同时保留原有顺序。

Kata.arrayDiff(new int[] {1, 2}, new int[] {1}) => new int[] {2}

如果某个值在b中存在,需要移除其在另一个列表中的所有出现:

Kata.arrayDiff(new int[] {1, 2, 2, 2, 3}, new int[] {2}) => new int[] {1, 3}

你的代码

public static int[] arrayDiff(int[] a, int[] b) {
    int[] result;
    int size = a.length;
    if (a.length == 0 || b.length == 0) {
        return a
    } else {
        for (int i = 0; i < b.length; i++) {
            for (int j = 0; j < a.length; j++) {
                if (a[j] == b[i]) {
                    size--;
                }
            }
        }
        result = new int[size];
        int index = 0;
        int countEq = 0;
        for (int i = 0; i < a.length; i++) {
            countEq = 0;
            for (int j = 0; j < b.length; j++) {
                if (a[i] == b[j]) {
                    countEq++;
                }
            }
            if (countEq == 0) {
                result[index] = a[i];
                index++;
            }
        }
    }
    return result;
}

代码存在的错误

  1. 语法错误:if分支里的return a语句末尾缺少分号,这会直接导致代码编译失败,CodeWars的编译检查会严格拦截这个问题。
  2. 逻辑错误:计算结果数组长度size时,若b中存在重复元素(比如b = [2,2]),会对a中同一个符合条件的元素重复减少size,导致size计算偏小。后续创建的数组长度不足,向数组写入元素时会触发ArrayIndexOutOfBoundsException。

修复方案

  1. 补上return a后的分号,解决语法问题。
  2. 对b中的元素去重后再统计,避免重复计数。推荐用HashSet存储b的元素,这样判断元素是否存在的效率更高,也能避免重复计算。

修复后的示例代码:

import java.util.HashSet;
import java.util.Set;

public class Kata {
    public static int[] arrayDiff(int[] a, int[] b) {
        Set<Integer> excludeSet = new HashSet<>();
        for (int num : b) {
            excludeSet.add(num);
        }
        
        // 统计结果数组长度
        int resultLength = 0;
        for (int num : a) {
            if (!excludeSet.contains(num)) {
                resultLength++;
            }
        }
        
        // 填充结果数组
        int[] result = new int[resultLength];
        int index = 0;
        for (int num : a) {
            if (!excludeSet.contains(num)) {
                result[index++] = num;
            }
        }
        return result;
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 11:40:44