【问题标题】:Finding the intersection of two arrays [closed]查找两个数组的交集[关闭]
【发布时间】:2012-10-16 16:25:47
【问题描述】:

我的目标是找出数组 a 和 b 的交集值并将它们存储到新数组 c 中,因此打印输出将为:3,10,4,8。如何将给定值分配给第三个数组 c ?

 public static void main(String[] args) {
        int a[] = {3, 10, 4, 2, 8};
        int[] b = {10, 4, 12, 3, 23, 1, 8};
        int[] c;
        int i=0;
         for(int f=0;f<a.length;f++){
              for(int k=0;k<b.length;k++){
                    if(a[f]==b[k]){
 //here should be a line that stores equal values of 2 arrays(a,b) into array c
            }
          }
        }
            for (int x=0; x<c.length; x++){
             System.out.println(c[i]);
            }
       }
  }

【问题讨论】:

标签: java arrays intersection


【解决方案1】:

这应该是一种简单的方法。

int a[] = {3, 10, 4, 2, 8};
int[] b = {10, 4, 12, 3, 23, 1, 8};
List<Integer> aList =  Arrays.asList(a);
List<Integer> bList =  Arrays.asList(b);
aList.retainAll(bList);
System.out.println(" a intersection b "+aList);
int[] c = aList.toArray(new int[0]);

【讨论】:

  • 谢谢。我确信这会做一些我需要的事情,但我还不熟悉 ArrayLists。
  • 这不会编译。一方面,因为Arrays.asList 返回了List&lt;int[]。第二,toArray 永远无法接收原始类型的数组。泛型不适用于基元。
【解决方案2】:
public static void main(String[] args) {
        int a[] = {3, 10, 4, 2, 8};
        int[] b = {10, 4, 12, 3, 23, 1, 8};
        int[] c = new int[(int)Math.min(a.length, b.length)];
        int i=0;
         for(int f=0;f<a.length;f++){
              for(int k=0;k<b.length;k++){
                    if(a[f]==b[k]){
                    c[i] = a[f];
                    i++;
            }
          }
        }
        for (int x=0; x<i; x++){
           System.out.println(c[x]);
        }
       }
  }

希望对您有所帮助。或者,如果您有时间复杂度问题,请尝试Java Set

【讨论】:

    【解决方案3】:

    首先你需要为你的数组分配空间:

    int[] c = new int[SOME_SIZE];
    

    困难的部分是弄清楚SOME_SIZE 应该是多少。由于您正在计算交集,因此它可以是ab 中最小的一个的大小。

    最后,要在数组中分配一个元素,您只需这样做

    c[idx] = a[f]
    

    现在您需要跟踪idx 的去向。我建议从idx = 0 开始,每次找到要添加到c 的新元素时递增它。

    【讨论】:

    • 这对初学者来说很困惑。但是谢谢你:)
    • @AlexandrMelnik 如果您感到困惑,我建议您尝试编写一个将一个数组复制到另一个数组的程序。如果您在这个更简单的程序中使用数组仍然有问题,那么您应该阅读更多关于它们的内容,并提出一些具体问题以供澄清。
    【解决方案4】:

    如果允许对 c 使用 ArrayList,它的可增长数组

    ArrayList c = new ArrayList();
    .
    .
    .
    .
    .
    c.add(a[f]);
    

    如果允许对数组进行排序,我建议您对较小的数组进行排序,然后迭代较大的数组并在较小的数组中进行二进制搜索。

    【讨论】:

    • 我认为你应该澄清一下,如果允许的话,这是一个很好的解决方案。据我们所知,OP 的项目可能存在一些不允许使用 ArrayList 的限制。
    • 谢谢。我确信这会做一些我需要的事情,但我还不熟悉 ArrayLists。
    【解决方案5】:

    您可以借助临时变量(但这基本上是在重新发明轮子,如果您不需要这样做的话)-

    int[] c = new int[0];
    //...
        if(a[f] == b[k]) { 
            int[] temp = c;
            c = new int[c.length + 1];
            for(int i=0; i<temp.length; i++) {
                c[i] = temp[i];
            }
            c[c.length - 1] = a[f];
        }
    //...
    

    【讨论】:

    • 只要两种方式都正确,我可以选择其中任何一种 :) 谢谢
    猜你喜欢
    • 1970-01-01
    • 2015-07-26
    • 1970-01-01
    • 1970-01-01
    • 2013-07-25
    • 2012-05-12
    • 2015-12-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多