【问题标题】:Union of 2 arrays in java?java中2个数组的联合?
【发布时间】:2011-08-14 15:41:39
【问题描述】:

我的代码

class Union {

    //Search Function
    static boolean search(int A[], int i) {

        for (int k = 0; k < A.length; k++) {
            if (A[k] == i) {
                return true;
            }
        }
        return false;
    }

    //union
    static void union(int A[][], int B[][]) {

        int i = 0;
        int count = 0;
        int C[] = new int[A.length + B.length];

        for (; i < A.length; i++) {
            if (!(search(B, A[i]))) {
                C[count] = A[i];
                count++;
            }
        }

        for (; i < (A.length + B.length); i++) {
            C[count] = B[i - A.length];
            count++;
        }

        System.out.println("This is Union Of 2 D Array ");
        System.out.println();

        for (int k = 0; k < count; k++) {
            System.out.println(C[k]);
        }
        System.out.println();

    }

    public static void main(String... s) {
        union(new int[]{1, 1, 1, 4,}, new int[]{1, 4, 4, 4, 1, 2});
    }
}

我正在使用此输出来查找二维数组的联合。但是我得到的输出是错误的。我不希望 2 在 java 中使用任何预定义的接口和方法。 我的回答应该是 {1,2,4}

示例

A= {1,2,3,3}
B={2,3,1,1}
c={1,2,3}

【问题讨论】:

  • 您的代码似乎只有一维数组。二维数组在哪里?
  • 如果我在这段代码中有错误,请纠正我
  • @Guarav_Java:当我们不知道您在寻找什么时,很难纠正您 - 但彼得是对的,您 只使用一维数组。请注意,数组类型变量的惯用声明是将所有类型信息放在一起:int[] x 而不是int x[]。此外,参数名称通常采用驼峰命名法。
  • 一个二维数组需要二维,即union(int[][] a, int[][] b),这就是它成为二维(二维)数组的原因。
  • @Gaurav_Java 请看我的回答:)

标签: java arrays multidimensional-array


【解决方案1】:

这就是你要找的:

import java.util.Arrays;

public class Union
{

    public static void main(String[] args)
    {
        int[] A = {1, 2, 3, 3};
        int[] B = {2, 3, 1, 1};
        System.out.println(Arrays.toString(unionArrays(A, B)));
    }

    /* Union of multiple arrays */
    public static int[] unionArrays(int[]... arrays)
    {
        int maxSize = 0;
        int counter = 0;

        for(int[] array : arrays) maxSize += array.length;
        int[] accumulator = new int[maxSize];

        for(int[] array : arrays)
            for(int i : array)
                if(!isDuplicated(accumulator, counter, i))
                    accumulator[counter++] = i;

        int[] result = new int[counter];
        for(int i = 0; i < counter; i++) result[i] = accumulator[i];

        return result;
    }

    public static boolean isDuplicated(int[] array, int counter, int value)
    {
        for(int i = 0; i < counter; i++) if(array[i] == value) return true;
        return false;
    }
}

输出:

[1, 2, 3]

【讨论】:

  • int[] A = {4,5,6 }; int[] B = { 1,2, 3,5, 1, 1 };此输入失败
【解决方案2】:

没有具体回答您的问题,但如果您实际上只是想获得一个联合,您可能应该使用 java Set 接口。详情请见here

【讨论】:

    【解决方案3】:

    当您想要唯一性时,Set 是一个自然的选择。为了避免大量的转换,你可以将int[]改为Integer[],得到一个非常简洁干净的union方法。

    这是一个完整的工作示例:

    import java.util.*;
    
    public class Union {
      // Search Function
      public boolean search(Integer a[], Integer i) {
        for(int k = 0; k < a.length; k++) {
          if(a[k] == i) {
            return true;
          }
        }
        return false;               
      }
    
      // Union
      public void union(Integer[] a, Integer[] b) {
        Set<Integer> set = new HashSet<Integer>(Arrays.asList(a));
        set.addAll(Arrays.asList(b));
        Integer[] unionArray = set.toArray(new Integer[set.size()]); 
        System.out.println(Arrays.toString(unionArray));
      }
    
      public static void main(String...s) {
        Integer[] array1 = new Integer[]{1,1,1,4,};
        Integer[] array2 = new Integer[]{1,4,4,4,1,2};
        new Union().union(array1, array2);
      }
    }
    

    显然,这里有开销从数组转换为列表,然后将该列表设置为集合,然后将该集合转换回数组。但是,通常不值得使用执行速度更快的复杂代码 - 只有当您发现在这部分代码中存在性能瓶颈时,才需要采用直接且更长(代码方面)的解决方案。

    使用 Set 还可以避免一个常见的错误,即遍历数组以搜索元素以确认要添加的元素不是重复的。通常,诸如此类的解决方案具有 O(n^2) 时间复杂度(请参阅this)。

    当您的数组有 10 个元素时,这不会成为问题,但如果您有两个数组,例如,每个数组有 1000 个唯一元素,您将进行大量不必要的遍历,从而使您的代码非常慢。在这种情况下,在通过遍历数组进行重复检查的基于数组的解决方案中,您将必须执行 1000 * 1000 / 2 = 500K 操作,而基于集合的操作将接近 5k:

    • 1000 将第一个数组转换为列表,
    • 1000 将列表转换为集合,
    • 1000 将第二个数组转换为列表,
    • 1000 将第二个数组添加到集合中
    • 1000 将其从集合中转换回一个数组)

    因为基于集合的解决方案是 O(n)。如果您假设这些操作大致相同(不正确,但仍然不是一个糟糕的近似值),这将快 100 倍。

    此外,这会随着唯一元素数量的增加而迅速增加 - 对于每个数组中的 10K 个元素,基于数组的遍历解决方案将需要 50,000,000 次操作,而基于集合的解决方案将需要 15,000 次.

    希望这会有所帮助。

    【讨论】:

    • @icyrocks。很好的答案谢谢这将帮助你。但我被限制不使用这些功能和预定义的方法
    【解决方案4】:

    您发布的代码处理一维数组,而不是二维 =) 代码似乎尝试将两个数组的内容连接到另一个数组中。为此,只需执行以下操作:

    public static int[] joinArrays(int[] a, int[] b) {
        if (a == null || b == null)
            throw new IllegalArgumentException("Both arrays must be non-null");
        int c[] = new int[a.length + b.length];
        System.arraycopy(a, 0, c, 0, a.length);
        System.arraycopy(b, 0, c, a.length, b.length);
        return c;
    }
    

    【讨论】:

    • 我希望它在不使用 System.arraycopy 的情况下运行
    【解决方案5】:

    A = {1,1,1,4} B = { 1,4,4,4,1,2}

    从数学上讲,集合 A 和 B 的并集是 C = {1,4,2}

    或者你想要重复,例如,C = {1,1,1,1,1,2,4,4,4,4}

    您的预期输出是哪一个?第一个还是第二个?

    public class Union_2{
    static int size;
    
    public static void main(String [] args){
    int [] a = {1,1,1,4};
    int [] b = {1,4,4,4,1,2};
    int [] c = Union_finder(a,b);
    for(int i = 0 ; i< size ; i++){
      System.out.print(c[i]+" ");
    }
    }
    public static int[] Union_finder(int [] a,int [] b){
    int [] c = new int[a.length+b.length];
    int i=0,j=0,k=0;
    for(;i<a.length;i++){
      boolean bool = check(a[i],c);
      if( bool == false){
        c[k] = a[i];
        size++;
        k++;
      }
    }
    for(;j<b.length;j++){
      boolean bool = check(b[j],c);
      if( bool== false){
        c[k] = b[j];
        size++;
        k++;
      }
    }
    return c ;
    }
    public static boolean check(int x,int [] c){
    if(size == 0){
      return false;
    }
    else{
      for(int i = size - 1 ; i >= 0 ; i--){
        if( c[i] == x){
          return true ;
        }
      }
    }
    return false ;
    }
    }
    

    【讨论】:

    • 首先输出这个你在回答中的帖子也可以在评论中完成
    • 我添加了你要找的代码,它找到了两组的并集并显示结果,希望对你有帮助。
    【解决方案6】:

    // 我希望这个例子简单。 //传递两个数组,你肯定会得到没有重复项的数组UNION。

    公共类 UnionOfArrays { public int[] getUnion(int[] arr1, int[] arr2) { int[] array = MergeSort.mergeArray(arr1, arr2); int[] arrReturn = getunique(array); return arrReturn; } public int[] getunique(int[] array) { int[] arrTemp = new int[array.length]; int[] arrReturn; int index = 0; for (int i = 0; i < array.length; i++) { Boolean found = false; for (int j = 0; j < i; j++) { if (array[i] == array[j]) { found = true; break; } } if (!found) { arrTemp[index++] = array[i]; } } arrReturn = new int[index]; for (int i = 0; i < index; i++) { arrReturn[i] = arrTemp[i]; } return arrReturn; }}

    【讨论】:

      【解决方案7】:
       public static int[] arrayUnion(int a1[], int a2[]){
              int[] resultArray={};
              ArrayList<Integer> arrayList = new ArrayList<Integer>();
      
              if(a1.length>a2.length){
                  resultArray=new int[a1.length];
              }else resultArray=new int[a2.length];
      
              for(int element : a1){
                  arrayList.add(Integer.valueOf(element));
      
              }
              for(int element:a2){
                  if(! arrayList.contains(element)){
                      arrayList.add(Integer.valueOf(element));
                  }
              }
      
              resultArray = arrayList.stream().mapToInt(i->i).toArray(); // only in java 8
             return  resultArray;
      
          }
      

      【讨论】:

        【解决方案8】:
            Set<String> set = new HashSet<>(list1);
            set.addAll(list2);
            List<String> union = new ArrayList<>(set);
        

        【讨论】:

          【解决方案9】:

          我希望这个例子是简单的一个。通过两个数组,你肯定会得到数组的 UNION 而没有重复项。

          private static int[] FindUnionOfTwoArray(int[] array1, int[] array2) {
                  Map<Integer,Integer> map=new HashMap<>();
                  for (int element : array1) {
                      map.put(element, element);
                  }
                  for (int element : array2) {
                      map.put(element, element);
                  }
                  int[] newArray=new int[map.size()];
                  int con=0;
                  for(Map.Entry<Integer, Integer> lst:map.entrySet()) {
                      newArray[con]=lst.getValue();
                      con++;
                  }
                  return newArray;
              }
          

          【讨论】:

            【解决方案10】:
            public static int doUnion(int a[], int n, int b[], int m) 
            {
                    HashSet<Integer> hs = new HashSet<Integer>(); 
                      
                    for (int i = 0; i < n; i++)  
                        hs.add(a[i]);         
                    for (int i = 0; i < m; i++)  
                        hs.add(b[i]); 
                    return hs.size();
            }
            

            【讨论】:

              猜你喜欢
              • 2019-10-17
              • 1970-01-01
              • 1970-01-01
              • 2013-10-14
              • 1970-01-01
              • 2013-06-19
              • 1970-01-01
              • 2011-04-15
              • 1970-01-01
              相关资源
              最近更新 更多