【问题标题】:Differences Between Two Integer Collection两个整数集合之间的差异
【发布时间】:2010-12-23 08:43:30
【问题描述】:

我有两组整数(即第一个是:2,3,4,5,第二个是 1,2,3,6)。如何找到加法数组(1,6)和减法数组(4,5)?我说收藏,但我把它们放在 Set 但是如果你有任何其他想法,我也可以使用它。我也会在不同的集合中保留加法和减法。

【问题讨论】:

标签: java collections set int


【解决方案1】:

我假设您指的是一组中的元素,而不是另一组中的元素。

Set<Integer> first = new LinkedHashSet<Integer>(Arrays.asList(2,3,4,5));
Set<Integer> second = new LinkedHashSet<Integer>(Arrays.asList(1,2,3,6));
Set<Integer> addition = subtract(first, second);
Set<Integer> subtracted = subtract( second, first);

public static <T> Set<T> subtract(Set<T> set1, Set<T> set2) {
    Set<T> ret = new LinkedHashSet<T>(set1);
    ret.removeAll(set2);
    return ret;
}

【讨论】:

  • 你知道算法效率是多少(用大O符号表示)吗?
  • Thinking In Java, 第 4 版, p. 中推荐了该算法。 456.跨度>
  • 对于 N 个元素,subtract() 的复杂度接近 O(N)。如果速度很关键,我建议使用 TIntHashSet,但我相信 LinkedHashSet 会很好。
【解决方案2】:

不确定这是否是您需要的,但您可以使用 google guava

import java.util.HashSet;
import java.util.Set;

import com.google.common.collect.Sets;


public class NumbersTest {

    public static void main(String[] args) {
        Set<Integer> set1 = new HashSet<Integer>(){{add(2);add(3);add(4);add(5);}};
        Set<Integer> set2 = new HashSet<Integer>(){{add(1);add(2);add(3);add(6);}};
        System.out.println("Nums Unique to set1: " + Sets.difference(set1, set2));
        System.out.println("Nums Unique to set2: " + Sets.difference(set2, set1));
    }
}

输出:

Nums Unique to set1: [4, 5]
Nums Unique to set2: [1, 6]

【讨论】:

    【解决方案3】:

    绝对不是最好的解决方案,但是..

    public class IntsFind {
    public static void main(String[] args) {
        List<Integer> first = Arrays.asList(2, 3, 4, 5);
        List<Integer> second = Arrays.asList(1, 3, 4, 6);
    
        List<Integer> missing = new LinkedList<Integer>();
        List<Integer> added = new LinkedList<Integer>(second);
    
        for (Integer i : first) {
            if (!added.remove(i)) {
                missing.add(i);
            }
        }
    
        System.out.println("Missing ints in second: " + missing);
        System.out.println("New ints in second: " + added);
    }
    

    }

    打印:

    第二个中缺少整数:[2, 5] 秒内的新整数:[1, 6]

    编辑不需要包装 Arrays.asList,正如@Peter Lawrey 所指出的那样

    【讨论】:

    • 对于这种操作,A set 是更自然的选择。也不需要用 LinkedList 包装 Arrays.asList。
    • .. 以及我实际使用这个“for”循环所做的事情 - @Peter Lawrey 回答更好地显示了减法
    猜你喜欢
    • 2021-07-25
    • 2018-01-07
    • 1970-01-01
    • 2016-07-31
    • 2010-09-08
    • 2010-11-24
    • 2019-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多