gpt4 book ai didi

java - 难倒: Detect identical sequence of integers in two integer arrays

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:54:37 25 4
gpt4 key购买 nike

首先,我是一个 java 新手。我一直在寻找一种不涉及列表或哈希表的简洁方法来解决这个问题,但还没有找到:

**请注意,这不是家庭作业,而是“构建 Java 程序”第 7 章中的练习 #14

编写一个名为 contains 的方法,它接受两个整数数组作为参数,并返回一个 boolean 值指示第二个数组的元素是否出现在第一个数组中。

例子:

Integer[] list1 = {1,6,2,1,4,1,2,1,8};

Integer[] list2 = {1,2,1};

调用 contains(list1, list2) 将返回 true。我想到了可以遍历数组的嵌套 for 循环,但我看不到明确的解决方案:

public static Boolean contains(Integer[] listOfNumbers1, Integer[] listOfNumbers2){

for(int i = 0 ; i < listOfNumbers2.length; i++){

for(int j = 0 ; j < listOfNumbers1.length; j++){

}
}

return true;
}

最佳答案

(您并没有真正指定是否需要考虑重复项,从您的示例来看,您似乎在尝试查看 array1 是否按顺序包含 array2 的所有元素)

有几种不同的情况需要考虑:

1. array2 is longer than array1:
if this is the case the result must be false because array1 can't
possibly have the same elements in order since array2 is longer

2. array2 is the same size as array1:
for this step you can use a single loop and compare the elements in order,
if you find a mismatch then array1 does not contain array2

for i from 0 to length do
if array1[i] != array2[i]
// false
end
end
// true

3. array2 is shorter than array1:
for this case you need to examine every array2.length elements from array1
and see if they match array2

matches = 0
for i from 0 to array1.length do
for j from 0 to array2.length do
if array1[i] == array2[j]
// increment i
// increment matches
end
end
if matches == array2.length
// true
else
// false
end
matches = 0 // reset matches
end

关于java - 难倒: Detect identical sequence of integers in two integer arrays,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13716175/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com