我一直在编写函数,这些函数可以在Java中找到两个集合的联合和交集,但是我的算法在某个地方似乎有问题。例如,当我输入以下两个数字向量时:
A = {0, 1, 3, 4, 5}
B = {1, 1, 2, 3, 4, 5, 6, 7, 8}我收到以下消息:
Union = {1, 1, 2, 3, 4, 5, 6, 7, 8}
Intersection = {0, 1, 3, 4, 5}这显然是不正确的。我应该收到:
Union = {0, 1, 2, 3, 4, 5, 6, 7, 8}
Intersection = {1, 3, 4, 5}下面是我的主代码中关于交叉口/联合的代码:
Vector<Inty> p1Shingles = new Vector<Inty>();
p1Shingles.add(new Inty(0));
p1Shingles.add(new Inty(1));
p1Shingles.add(new Inty(3));
p1Shingles.add(new Inty(4));
p1Shingles.add(new Inty(5));
Vector<Inty> p2Shingles = new Vector<Inty>();
p2Shingles.add(new Inty(1));
p2Shingles.add(new Inty(1));
p2Shingles.add(new Inty(2));
p2Shingles.add(new Inty(3));
p2Shingles.add(new Inty(4));
p2Shingles.add(new Inty(5));
p2Shingles.add(new Inty(6));
p2Shingles.add(new Inty(7));
p2Shingles.add(new Inty(8));
Vector<Inty> shinglesUnion = vectorUnion(p1Shingles, p2Shingles);
Vector<Inty> shinglesIntersection = vectorIntersection(p1Shingles, p2Shingles);这里,Inty是我创建的一个类,这样我就可以更改我需要存储在向量中的整数的值,这在Integer类中是不可能的。下面是我编写的函数:
private static <T> Vector<T> vectorIntersection(Vector<T> p1Shingles, Vector<T> p2Shingles)
{
Vector<T> intersection = new Vector<T>();
for(T i : p1Shingles)
{
if(p2Shingles.contains(i))
{
intersection.add(i);
}
}
return intersection;
}
private static <T> Vector<T> vectorUnion(Vector<T> p1Shingles, Vector<T> p2Shingles) {
Vector<T> union = new Vector<T>();
union.addAll(p2Shingles);
for(T i : p1Shingles)
{
if(!p2Shingles.contains(i))
{
union.add(i);
}
}
return union;
}如果有人能深入了解为什么这不起作用的话,我很想听听。提前感谢!
发布于 2014-08-05 22:20:30
方法isDuplicated不使用参数i!实际上,我认为它总是返回True。将函数的整个代码替换为
return p2Shingles.contains(i)应该就够了。
https://stackoverflow.com/questions/25149087
复制相似问题