英文:
How to get the common values in an array (Java)?
问题
public class TwoLists {
static void arrs() {
int[] list1 = {1, 6, 2, 1, 4, 1, 2, 1, 8};
int[] list2 = {1, 2, 1};
for (int i = 0; i < list1.length - 1; i++) {
for (int o = i + 3; o < list1.length; o++) {
for (int out1 = list1[i]; out1 == list1[o]; out1++) {
System.out.print(out1);
}
}
}
}
public static void main(String[] args) {
arrs();
}
}
英文:
I want to get the common values of list1 and compare it to list2. I got an output of 11121 instead of 121. How can I resolve this?
Here's my code:
public class TwoLists {
static void arrs() {
int[] list1 = {1, 6, 2, 1, 4, 1, 2, 1, 8};
int[] list2 = {1, 2, 1};
for(int i = 0; i < list1.length-1; i++)
{
for(int o = i+3; o < list1.length; o++)
{
for(int out1 = list1[i]; out1 == list1[o]; out1++)
{
System.out.print(out1);
}
}
}
}
public static void main(String[] args)
{
arrs();
}
}
答案1
得分: 0
尝试以下操作:
- 使用
Set<Integer>
记录已找到的值。 - 然后使用嵌套数组遍历每个数组,从开始到结束。
- 在外部循环中,检查
set.contains()
是否包含当前值。 - 如果是,继续外部循环。
- 否则,比较内部和外部列表的值。
- 当找到匹配时,打印该值,添加到集合中,然后跳出内部循环。
- 继续外部循环中的下一个值。
还有其他更快的方法,只使用集合,但这可以作为一个开始。
英文:
Try the following:
- Use a
Set<Integer>
to record those already found. - then use a nested array going from start to finish for each array
- in the outer loop, see if
set.contains()
the current value. - if so, continue outer loop.
- otherwise, compare inner and outer list values.
- when a match is found, print it, add to the set, and then break out of the inner loop.
- continue next value in outer loop.
There are other, faster ways using just sets exclusively but this would serve as a start.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论