gpt4 book ai didi

java - Java 中集合的并集和交集计算错误

转载 作者:行者123 更新时间:2023-12-01 12:40:30 24 4
gpt4 key购买 nike

我一直在编写在 Java 中查找两个集合的并集和交集的函数,但我的算法似乎在某个地方存在问题。例如,当我输入以下两个数字 vector 时:

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}

这是我的 main 中与交集/并集相关的代码:

    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 是我创建的一个类,这样我就可以更改需要存储在 vector 中的整数的值,而这对于 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;
}

如果有人能给出任何关于为什么这不起作用的见解,我很想听听。预先感谢!

最佳答案

方法isDuplicated不使用参数i!实际上我认为它总是返回True。将函数的整个代码替换为

return p2Shingles.contains(i)

应该够了。

关于java - Java 中集合的并集和交集计算错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25149087/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com