java - 阵列的工作结构。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。
解决方案
问题是,一旦您teamB
在循环中更新数组,数组就不再排序。并且在未排序的数组中,二进制搜索会给出意想不到的输出。
推荐阅读
- android - 如何在android中从剩余百分比下载文件(第一次下载停止)
- php - 我将如何回应尚未确认其电子邮件的用户
- compilation - Perl 6 中后缀或后缀之前的点是什么意思?
- postfix - 滥用 - SASL 登录身份验证失败:UGFzc3dvcmQ6
- ios - 如何更新另一个 UIViewController - SWIFT 上的进度视图?
- python-3.x - 使用 pip-python 3.6 安装 flask-pymongo
- assembly - 将 2 个寄存器作为一个移位
- c++ - C++ 代码在 Linux 上按预期工作,但在 Windows 上不工作
- c++ - CMake:从 src 和其他静态库构建共享库
- javascript - 用 Javascript 替换单词而不删除图像