简体   繁体   English

两个 arrays 的交集(索引越界异常)

[英]Intersection of two arrays (index out-of-bound exception)

I want to compute the intersection of two arrays.我想计算两个 arrays 的交集。 My implementation leads to ArrayIndexOutOfBoundException in the line.. a[index++]=nn.我的实现导致ArrayIndexOutOfBoundException in the line.. a[index++]=nn. . . Please help me to find the mistake:请帮我找出错误:

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]
class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        int n;
          Set<Integer> s1=new HashSet<Integer>();
        Set<Integer> s2=new HashSet<Integer>();
        int a[]=new int[Math.abs(s1.size()-s2.size())];
        int index=0;
        if(nums1.length==0|| nums2.length==0){
            return a;
        }
        for(int n1:nums1){
            if(!s1.contains(n1))
                s1.add(n1);
        }
        for(int n2:nums2){
            if(!s2.contains(n2))
                s2.add(n2);
        }
        for(int nn:s1){
            if(s2.contains(nn))
                a[index++]=nn;
        }
        return a;
    }
}

You are quite close to the solution: you have to use the Set method retainAll for the intersection like below:您非常接近解决方案:您必须对交叉点使用Set方法retainAll ,如下所示:

public static int[] intersection(int[] nums1, int[] nums2) {
    if (nums1.length == 0 || nums2.length == 0) { return null; }
    Set<Integer> s1 = new HashSet<Integer>();
    Set<Integer> s2 = new HashSet<Integer>();

    for (int n1 : nums1) { s1.add(n1); }
    for (int n2 : nums2) { s2.add(n2); }

    s1.retainAll(s2);
    if (s1.isEmpty()) { return null; }
    int[] result = new int[s1.size()];
    int i = 0;
    for (int n : s1) { result[i++] = n; }
    return result;
}

With Set add there is no need to check if the element to be added is already present in your set.使用Set add无需检查要添加的元素是否已存在于您的集合中。 I chose to return null in the case at least one of the arrays is empty or when their intersection is empty too.我选择返回null ,以防 arrays 中的至少一个为空或它们的交叉点也为空。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM