找到交集

时间:2015-11-18 11:53:03

标签: java arrays intersection

我必须找到两个Set对象之间的交集。

2 个答案:

答案 0 :(得分:3)

变量intCount在最里面的if条件中是本地的,这意味着只访问interArr的第一个条目。重新排列实现如下。

public int[] intersection(Set parSet)
{
    int[] interArr = new int[numbers.length];
    int[] testArr = parSet.toArray();

    int intCount = 0; // initialization out of the loop

    for(int index = 0; index < numbers.length; index++)
    {
        for(int compareInt = 0; compareInt < testArr.length; compareInt++)
        {
            if(numbers[index] == testArr[compareInt])
            {
                interArr[intCount] = testArr[compareInt];
                intCount++;
            }//end if
        }//end inner for
    }//end outter for

    return interArr;
}//end method intersection

答案 1 :(得分:1)

你走在正确的轨道上:使用嵌套循环进行详尽的搜索(虽然可以使用java集合进行简化),但只有一些小问题:

1)您没有为您的班级定义toArray()方法,所以假设您在致电parSet.numbers时意味着parSet.toArray()

2)计数器intCount需要在循环之外,以避免在每次迭代中设置为0。

所以正确的版本应该是:

public int[] intersection(Set parSet) {
    int[] interArr = new int[numbers.length];
    int[] testArr = parSet.numbers; //you didn't define toArray() for the class Set
    int intCount = 0; // move this variable out of the loop
    for (int index = 0; index < numbers.length; index++) {
        for (int compareInt = 0; compareInt < testArr.length; compareInt++) {
            if (numbers[index] == testArr[compareInt]) {
                interArr[intCount] = testArr[compareInt];
                intCount++;
            }//end if
        }//end inner for
    }//end outter for

    return interArr;
}//end method intersection