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

为何Java中Binary Search无法找到全部重复目标元素?

问题原因&修复方法

为啥只输出1?

原代码里的break是核心问题——每次找到匹配的元素后,直接执行break跳出了整个循环,导致bricksNeeded里的第二个"BBBB"根本没机会被处理,自然只统计到1个。

另外补充个小优化:bricks.remove(bricks.get(index))可以直接写成bricks.remove(index),效果一致还更高效。

修复方案1:移除break语句

直接删掉循环里的break,让循环遍历完bricksNeeded的所有元素:

import java.util.*;

public class Test{
    public static void main(String[] args) {
        ArrayList<String> bricks = new ArrayList<>(List.of("BBBB","BBBB","CCCC"));
        ArrayList<String> bricksNeeded = new ArrayList<>(List.of("BBBB","BBBB"));
        int nFound = 0;
        int index;
        for(String brickNeeded:bricksNeeded){
            index = Collections.binarySearch(bricks, brickNeeded);
            if(index >= 0){
                bricks.remove(index);
                nFound ++;
                // 移除此处的break语句
            }
        }
        System.out.println(nFound);
    }
}

修复方案2:更高效的统计方式(无需反复修改数组)

如果你的需求只是统计可匹配的数量,不需要修改原数组,直接统计原数组中目标元素的总数,再和需要的数量取最小值即可,比反复执行二分查找+删除元素高效得多:

import java.util.*;

public class Test{
    public static void main(String[] args) {
        ArrayList<String> bricks = new ArrayList<>(List.of("BBBB","BBBB","CCCC"));
        ArrayList<String> bricksNeeded = new ArrayList<>(List.of("BBBB","BBBB"));
        
        // 统计原数组中"BBBB"的数量
        long availableCount = bricks.stream().filter("BBBB"::equals).count();
        // 取需要数量与现有数量的较小值
        int nFound = (int) Math.min(availableCount, bricksNeeded.size());
        
        System.out.println(nFound);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 02:15:22