gpt4 book ai didi

java - 多个数组的公共(public)元素但不使用列表

转载 作者:行者123 更新时间:2023-11-29 09:29:39 24 4
gpt4 key购买 nike

有没有办法在数组中返回 2 个或更多数组的公共(public)元素?我知道列表下的一些方法可以做到,但是有没有办法只使用数组来做到这一点?自从我创建一个名为 OrderedIntList 的数组以来,我自己制作了 get 和 length。

例如:

1,3,5

1,6,7,9,3

1,3,10,11

结果:1​​,3

我试过了,它输出两个数组之间的共同元素,而不是全部。我知道出了点问题,但我不知道如何让它像预期的那样工作:(

//返回输入数组的公共(public)元素

public static OrderedIntList common(OrderedIntList ... lists){ 

int[] list = new int[10];

for(int x = 1; x <= lists.length -1; x++){

for(int q = 0; q < lists[0].length()-1; q++) {

for(int z = 0; z < lists[x].length(); z++) {

if (lists[0].get(q)==lists[x].get(z)){
list[q] = lists[0].get(q);
}
}
}
}

OrderedIntList newlist = new OrderedIntList(list);

return newlist;
}

最佳答案

这可以是一个简单的算法来解决它...

    1) Instantiate an instance variable of type array called
"commonElements" pointing to the elements of the first Array. At the
beginning these are your common elements.

2) Create a method call getCommonElements(int[] commonElements,
int[] newList). This method manipulates the commonElements array to leave
it with only the common elements between the two. (p.s Use a temporary
array to achieve this if you find it easier)

3) Iterate over all the arrays present in "lists" starting from the
second array.

4) call the method at point 2 for each array .

对你来说所有困难的部分是实现一个给定的 2 个数组找到共同元素的方法!

关于java - 多个数组的公共(public)元素但不使用列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26087278/

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