首页 > 解决方案 > 阵列的工作结构。java中的binarySearch()方法

问题描述

我正在尝试解决字符串中的问题,在字符串中找到匹配的字符。我使用字符数组和内部循环来解决它,但我认为它的时间复杂度更高。所以尝试在数组二进制搜索中解决它,但它给出了不合适的结果。我想要java中二进制搜索方法的工作结构。

我在字符串二中设置了匹配值来复制字符'#',因为不想匹配另一个字符。

public static void main(String[] args) {

        Scanner s= new Scanner(System.in);


        String team1 = s.next();
        String team2 = s.next();

        char[] teamA = team1.toCharArray();
        char[] teamB = team2.toCharArray();

        Arrays.sort(teamB);

        int count = 0;
        for(int a=0;a< teamA.length;a++) {
            int index = Arrays.binarySearch(teamB, teamA[a]);

            if(index >= 0) {
                count++;
                teamB[index] = '#';
            }
        }
        System.out.println(count);
    }

如果我输入两个字符串“aabc”和“zbaa”,预期输出为 3,但我的程序给出输出 2。

标签: javaarraysbinary-search

解决方案


问题是,一旦您teamB在循环中更新数组,数组就不再排序。并且在未排序的数组中,二进制搜索会给出意想不到的输出。


推荐阅读