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

求两列表有序公共元素(允许重复)的Java代码提交错误排查

问题排查与修复

核心错误点

  • Integer包装类比较逻辑错误
    Java中Integer是引用类型,直接使用==比较的是对象的内存地址,而非存储的数值。JVM默认只会缓存-128~127范围内的Integer对象,超出这个范围的相同数值的Integer对象用==判断会返回false,直接导致大量匹配漏判。
  • 修改原始输入列表的副作用
    代码直接对传入的v1、v2执行排序操作,会改变原输入列表的元素顺序,如果业务逻辑要求保留输入列表的原有顺序,会引发其他功能异常。

修复后代码

import java.util.ArrayList;
import java.util.Collections;

class Solution {
    public static ArrayList<Integer> common_element(ArrayList<Integer>v1, ArrayList<Integer>v2) {
        ArrayList<Integer> com = new ArrayList<>();
        // 复制原列表后再排序,避免修改输入参数
        ArrayList<Integer> sortedV1 = new ArrayList<>(v1);
        ArrayList<Integer> sortedV2 = new ArrayList<>(v2);
        Collections.sort(sortedV1);
        Collections.sort(sortedV2);
        
        int i = 0;
        int j = 0;
        while (i < sortedV1.size() && j < sortedV2.size()) {
            // 先拆箱为int基本类型再比较,规避引用比较问题
            int num1 = sortedV1.get(i);
            int num2 = sortedV2.get(j);
            if (num1 == num2) {
                com.add(num1);
                i++;
                j++;
            } else if (num1 > num2) {
                j++;
            } else {
                i++;
            }
        }
        return com;
    }
}

验证说明

原逻辑的双指针遍历逻辑本身是符合需求的,修复后即可正确处理所有数值范围的公共元素匹配,也不会影响输入列表的原始顺序。比如测试用例v1=[200,200,300]、v2=[200,200,200],原代码会返回空列表,修复后会正确返回[200,200]。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 23:48:00