Java 如何找到两个字符串数组的并集

Java 如何找到两个字符串数组的并集,java,arrays,Java,Arrays,我试图找到两个字符串数组的并集。我创建了一个新数组,并将第一个数组中的所有数据复制到新数组中。我无法将第二组的信息添加到新数组中 我需要使用循环来搜索第二个数组并找到重复的数组。我一直收到一个数组索引OutofBoundsException 这是我目前的代码: static String[] union(String[] set1, String[] set2) { String union[] = new String[set1.length + set2.length];

我试图找到两个字符串数组的并集。我创建了一个新数组,并将第一个数组中的所有数据复制到新数组中。我无法将第二组的信息添加到新数组中

我需要使用循环来搜索第二个数组并找到重复的数组。我一直收到一个
数组索引OutofBoundsException

这是我目前的代码:

static String[] union(String[] set1, String[] set2) {
    String union[] = new String[set1.length + set2.length];

    int i = 0;
    int cnt = 0;

    for (int n = 0; n < set1.length; n++) {
        union[i] = set1[i];
        i++;
        cnt++;
    }

    for (int m = 0; m < set2.length; m++) {
        for (int p = 0; p < union.length; p++) {
            if (set2[m] != union[p]) {
                union[i] = set2[m];
                i++;
            }
        }
    }
    cnt++;

    union = downSize(union, cnt);

    return union;
}
静态字符串[]联合(字符串[]集1,字符串[]集2){
字符串联合[]=新字符串[set1.length+set2.length];
int i=0;
int-cnt=0;
对于(int n=0;n
进行交点或并集的标准方法是使用集合。您应该使用集合框架中的
Set

为两个数组创建两个arraylist对象。
定义一个集合对象。
使用
addAll
方法将两个arraylist对象添加到集合中

因为集合包含唯一的元素,所以集合形成了元素的并集 两个阵列

  //push the arrays in the list.
  List<String> list1 = new ArrayList<String>(Arrays.asList(stringArray1));
  List<String> list2 = new ArrayList<String>(Arrays.asList(stringArray2));

  HashSet <String> set = new HashSet <String>();

  //add the lists in the set.
  set.addAll(list1);
  set.addAll(list2);

  //convert it back to array.
  String[] unionArray = set.toArray(new String[0]);       
//将数组推送到列表中。
List list1=新的ArrayList(Arrays.asList(stringArray1));
List list2=新的ArrayList(Arrays.asList(stringArray2));
HashSet=newhashset();
//在集合中添加列表。
set.addAll(列表1);
set.addAll(列表2);
//将其转换回数组。
String[]unionArray=set.toArray(新字符串[0]);

您可以在此行中获得ArrayIndexOutOfBoundsException:

union[i] = set2[m];
因为您一直在增加
i
的次数:
set2.length*union.length
次(嵌套循环)

做R.J写的不会给你联盟-你会有很多重复的项目,因为通过这样做:
set2[m].equals(union[p])
你会将set2的每个成员与联盟的所有成员进行比较,并且对于每个不相等的成员,你会添加它。因此,您最终会多次添加相同的项目

正确的方法就像Deepak Mishra建议的那样,使用
Set
来“处理”重复项

例如:

int[] a = {1,2,3,4,5};
int[] b = {4,5,6,7};
Set union = new HashSet<Integer>();
for(int i=0; i<a.length; i++) union.add(a[i]);
for(int i=0; i<b.length; i++) union.add(b[i]);
Object[] ans = union.toArray();
for(int i=0; i<ans.length; i++)
    System.out.print(ans[i]+" ");

因为它是HW,我不会为答案编写代码,但我会给你一个提示:
按照你的方式来做需要
O(n^2)
-如果你想一想,我相信你可以找到一种更好的时间来做,比如说,
O(n log n)
你的这部分代码有几个问题:

for(int m = 0; m < set2.length; m++)
        for(int p = 0; p < union.length; p++)
            if(set2[m] != union[p])
            {   
                union[i] = set2[m];
                i++;        
            }
        cnt++;

正如其他海报所指出的,另一种方法是使用
散列集
,添加在两个数组中找到的元素,然后将结果转换回数组。

使用
将是最简单的方法之一:

public static String[] unionOf(String[] strArr1, String[] strArr2) {
    Set<String> result = new HashSet<String>();
    result.addAll(Arrays.asList(strArr1));
    result.addAll(Arrays.asList(strArr2));
    return result.toArray(new String[result.size()]);
}

虽然使用集合是最好的解决方案,但这里有一个简单的解决方案

 private static String getUnion(String a, String b, boolean ignoreCase) {

    String union = "";

    if (a == null || b == null || a.length() < 1 || b.length() < 1) {
        return union;
    }

    char[] shortest;
    char[] longest;

    if (ignoreCase) {
        shortest = (a.length() <= b.length() ? a : b).toLowerCase().toCharArray();
        longest = (a.length() <= b.length() ? b : a).toLowerCase().toCharArray();
    } else {
        shortest = (a.length() <= b.length() ? a : b).toLowerCase().toCharArray();
        longest = (a.length() <= b.length() ? b : a).toLowerCase().toCharArray();
    }

    StringBuilder sb = new StringBuilder();

    for (char c : shortest) {
        for (int i = 0; i < longest.length; i++) {
            if (longest[i] == c) {
                sb.append(c);
            }
        }
    }

    union = sb.toString();

    return union;
}

非常感谢。我感谢你的指导。这非常有用。
boolean=set2[m].equals(union[p])-您的意思可能是:
found |=set2[m].equals(union[p])谢谢你的指导。这非常有帮助。我理解我的错误,并且对如何纠正错误有了更好的想法。@alfasin-Oops。谢谢你指出这一点。现在修好了。然而,人们不需要
|=
=
可以,因为除非
found
false
,否则不会输入循环体。对,我错过了for循环内的条件+1 :)
public static String[] unionOf(String[] strArr1, String[] strArr2) {
    Set<String> result = new HashSet<String>();
    result.addAll(Arrays.asList(strArr1));
    result.addAll(Arrays.asList(strArr2));
    return result.toArray(new String[result.size()]);
}
public static String[] unionOf(String[] strArr1, String[] strArr2) {
    return Sets.union(Sets.newHashSet(strArr1), 
                      Sets.newHashSet(strArr2))
               .toArray(new String[0]);
}
 private static String getUnion(String a, String b, boolean ignoreCase) {

    String union = "";

    if (a == null || b == null || a.length() < 1 || b.length() < 1) {
        return union;
    }

    char[] shortest;
    char[] longest;

    if (ignoreCase) {
        shortest = (a.length() <= b.length() ? a : b).toLowerCase().toCharArray();
        longest = (a.length() <= b.length() ? b : a).toLowerCase().toCharArray();
    } else {
        shortest = (a.length() <= b.length() ? a : b).toLowerCase().toCharArray();
        longest = (a.length() <= b.length() ? b : a).toLowerCase().toCharArray();
    }

    StringBuilder sb = new StringBuilder();

    for (char c : shortest) {
        for (int i = 0; i < longest.length; i++) {
            if (longest[i] == c) {
                sb.append(c);
            }
        }
    }

    union = sb.toString();

    return union;
}
public static void main(String[] args) {

    System.out.println("Union of '' and BXYZA is " + getUnion("", "BXYZA", true));
    System.out.println("Union of null and BXYZA is " + getUnion(null, "BXYZA", true));

    System.out.println("Union of ABC and BXYZA is " + getUnion("ABC", "BXYZA", true));
    System.out.println("Union of ABC and BXYZA is " + getUnion("ABC", "bXYZA", false));

}