【发布时间】:2018-05-28 21:46:37
【问题描述】:
您好,我是 Java 新手,我正在做这个实验任务,我们比较两个数组的元素以获得共同的元素。我被困在如何摆脱重复项上。
我当前的代码给了我输出 [3, 0, 5, 6, 5, 0, 9, 0],而想要的 common 输出是 [3, 5, 6, 9, 0, 0, 0, 0]。
另外,由于我没有那么有经验,请不要发布解决问题的专业方法或“有经验”的回答我的问题,因为这对我没有任何帮助:D。
谢谢!
public static void main (String[] args) {
int[] a1 = {3, 8, 5, 6, 5, 8, 9, 2};
int[] a2 = {5, 15, 4, 6, 7, 3, 9, 11, 9, 3, 12, 13, 14, 9, 5, 3, 13};
int[] common = new int[a1.length];
System.out.println("Exercise 3: ");
findCommon(a1,a2,common);
}
public static void findCommon(int[] a1, int[]a2, int[] common) {
int num = 0;
for (int i = 0; i < common.length; i++)
{
for (int j = 0; j < a2.length; j++)
{
if (a1[i] == a2[j]) // loops through every index of j, while keeping i at one index
num = a1[i];
for (int k = 0; k < common.length; k++) // makes sure there are no duplicates in common
{
if (num != common[k])
common[i] = num;
}
}
}
for (int elements : common)
System.out.print(elements + " ");
}
【问题讨论】:
-
好吧,不完全是重复的,尽管交集是在顶级解决方案中作为中间结果派生的。我喜欢this 的回答,因为它解决了数组方面的问题。
标签: java arrays for-loop foreach