简体   繁体   English

阵列的工作结构。 Java中的binarySearch()方法

[英]Working Sturcture of Arrays. binarySearch() method in java

I'm trying solve problem in Strings,finding matching characters in to String. 我正在尝试解决字符串中的问题,在字符串中找到匹配的字符。 I solve it using Character Array and inner loop but i think it has more time complexity. 我使用字符数组和内部循环来解决它,但是我认为它具有更多的时间复杂性。 so try to solve it in Arrays binary search but it gives inappropriate result.i want working structure of binary search method in java. 所以尝试在数组二进制搜索中解决它,但结果不适当。我想在Java中使用二进制搜索方法的工作结构。

I set matched value in the String two to duplicate char '#',because don't want to match another char. 我在字符串2中设置了匹配的值来复制字符'#',因为不想匹配另一个字符。

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);
    }

if i give input of two strings "aabc" and "zbaa" expected output is 3 but my program gives output 2. 如果我输入两个字符串“ aabc”和“ zbaa”,则预期输出为3,但我的程序输出为2。

The problem is that once you update the teamB array in the loop the array is no longer sorted. 问题是,一旦在循环中更新了teamB数组,该数组将不再排序。 And in unsorted array binary search will give unexpected outputs. 在未排序的数组中,二进制搜索将提供意外的输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM