【问题标题】:Union, intersect, difference large IntSet in O(m+n) times在 O(m+n) 次中联合、相交、差异大 IntSet
【发布时间】:2010-08-30 15:37:07
【问题描述】:

我的问题

Insert element to ArrayList with ascending order and no duplicate elements

我已经完成了我的插入方法。

现在我尝试找出如何构建并集、交集和差分方法来对 2 个 IntSet 进行操作。

注意 IntSet 的元素数量很大,我需要在 O(m+n) 时间内完成,其中 m 和 n 是两个 IntSet 的元素个数。

例如 IntSets

a = new IntSetExtra();
b = new IntSetExtra();

for(int i=0; i<300; i++){ a.insert(2*i); }
for(int i=0; i<300; i++){ a.insert(i); }

for(int i=20000; i<50000; i++){ b.insert(i); }

我该怎么做?

附:它可以使用归并排序吗?

编辑:

这是我的工会代码

public IntSetExtra union(IntSetExtra a){
    //effect: return new IntSet that union between this and a;
    IntSetExtra intSet = new IntSetExtra();
    intSet.addAll(a);
    for(int i=0; i<a.size(); i++){
        if(!intSet.contains(a.get(i))){
            intSet.insert(a.get(i));
        }
    }
    return intSet;
}

【问题讨论】:

  • 您真的应该自己解决其中的一些问题,然后将您尝试过/没有成功的事情反馈给我们。

标签: java set-difference set-intersection set-operations set-union


【解决方案1】:

你可以只使用addAll(Collection)removeAll(Collection)retainAll(Collection)等java集合的方法。

例如两个集合的交集:

public Set<V> intersection(Set<? extends V> a, Set<? extends V> b) {
  // you may swap a and b, so a would contain the smaller collection
  Set<V> result = new HashSet<V>(a);
  result.retainAll(b);
  return result;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多