检查字符数组是否包含Java中较小字符数组中的所有元素
我试图比较两个字符数组,其中第一个数组比第二个数组长一个字符。我想看看较大的数组是否包含较小数组中的所有字符 例如,给定数组:检查字符数组是否包含Java中较小字符数组中的所有元素,java,arrays,comparison,nested-loops,Java,Arrays,Comparison,Nested Loops,我试图比较两个字符数组,其中第一个数组比第二个数组长一个字符。我想看看较大的数组是否包含较小数组中的所有字符 例如,给定数组: char[] biggest = {'a', 'b', 'c', 'd', 'e'}; //5 elements char[] smallest = {'c', 'b', 'd', 'a'}; //4 elements 比较这些值应计算为true,因为较小的数组包含字符c、b、d和a,所有这些字符都包含在最大的数组中,而不考虑顺序 下面是我的想法: 从一个for循
char[] biggest = {'a', 'b', 'c', 'd', 'e'}; //5 elements
char[] smallest = {'c', 'b', 'd', 'a'}; //4 elements
比较这些值应计算为true,因为较小的数组包含字符c、b、d和a,所有这些字符都包含在最大的数组中,而不考虑顺序
下面是我的想法:
从一个for循环开始,循环遍历最大的数组,每次一个字符
查看是否可以在最小数组中找到当前字符
如果存在匹配项,则增加一个匹配计数器。
直到到达最大数组的末尾为止
如果匹配计数器等于smallestArray.length,则返回true。
以下是我的代码:
int matchCounter = 0;
//For each character in the biggest array
for(int i = 0; i < biggest.length; i++) {
//Loop through the smallest array
for(int j = 0; j < smallest.length; j++) {
if(biggest[i] == smallest[j]) { //See if the current character in the biggest array exists anywhere in the smallest array
matchCounter++;
}
}
}
因为如果不是这样的话,它似乎工作得很好 使用集合:
您的方法将给出正确的答案,但速度相当慢,因为您保证每次都在每个数组中循环,并提供On2运行时 在保持类似方法的同时,使这一过程更快的一种方法是对更大的集合进行排序。这允许您对较小集合中的每个字符进行二进制搜索,而不必每次都进行迭代:
int matchCounter = 0;
Arrays.sort(biggest);
for (char c : smallest) {
if (Arrays.binarySearch(biggest, c) >= 0) {
matchCounter++;
}
}
System.out.println(matchCounter); // 4
你的问题是什么?这的确是个不错的主意。不是100%的效率,但它是有效的。现在,有什么问题吗?
public static boolean allContained(char[] big, char[] small) {
Set<Character> chars = new HashSet<>(big.length);
for(char c : big) {
chars.add(c);
}
for(char c : small) {
if(!chars.contains(c)) {
return false; // small contains elements that are not in big
}
}
return true;
}
int matchCounter = 0;
Arrays.sort(biggest);
for (char c : smallest) {
if (Arrays.binarySearch(biggest, c) >= 0) {
matchCounter++;
}
}
System.out.println(matchCounter); // 4