【问题标题】:Find duplicate values in input在输入中查找重复值
【发布时间】:2015-07-27 18:29:38
【问题描述】:

我有这样的输入:

Apple: 0 1
Apple: 4 5
Pear: 0 10
Pear: 11 13
Apple: 5 10
Apple: 2 4

我正在寻找水果相同且第一个值等于另一行的第二个值的行。所以我正在寻找如下行:Apple: 4 5Apple: 2 4,我还需要Apple: 4 5Apple: 5 10

另一方面,我不想搜索整个数据。我的意思是我不想在Pears 中搜索Apple

我应该使用 HashMap 吗?还是哈希集?还是别的什么?

感谢您的回复。

【问题讨论】:

  • 您可以创建两个哈希图,每个水果一个,并使用“第一个”值作为键和一些值(例如布尔值)填充映射。然后对于同一水果的任何“第二”值,查看它是否在地图中。
  • 好吧,我明白了。但是如果我有超过 100 个水果呢?
  • 哈希表不是问题。

标签: java hashmap duplicates hashset


【解决方案1】:

试一试...它使用HashMapLists

public static void main(String[] args) {
    List<String> inputs = new ArrayList<>();
    inputs.add("Apple: 0 1");
    inputs.add("Apple: 4 5");
    inputs.add("Pear: 0 10");
    inputs.add("Pear: 11 13");
    inputs.add("Apple: 5 10");
    inputs.add("Apple: 2 4");

    Map<String, List<Fruit>> fruits = new HashMap<>();
    for (String input : inputs) {
        String[] inputPieces = input.split(" ");
        String name = inputPieces[0].replace(":", "");
        int first = Integer.parseInt(inputPieces[1]);
        int second = Integer.parseInt(inputPieces[2]);

        if (!fruits.containsKey(name)) {
            fruits.put(name, new ArrayList<Fruit>());
        }
        fruits.get(name).add(new Fruit(name, first, second));
    }

    for (String key : fruits.keySet()) {
        System.out.println(key + ": " + findDuplicates(fruits.get(key)));
    }
}

private static List<Fruit> findDuplicates(List<Fruit> fruits) {
    List<Fruit> results = new ArrayList<>();

    for (int i = 0; i < fruits.size(); i++) {
        for (int j = 0; j < fruits.size(); j++) {
            if (j == i) {
                continue;
            }

            if ((fruits.get(i).first == fruits.get(j).second) ||
                (fruits.get(j).first == fruits.get(i).second)) {
                if (!results.contains(fruits.get(i))){
                    results.add(fruits.get(i));
                }
            }
        }
    }

    return results;
}

public static class Fruit {
    private String name;
    private int first;
    private int second;

    public Fruit(String name, int first, int second) {
        this.name = name;
        this.first = first;
        this.second = second;
    }

    @Override
    public String toString() {
        return String.format("%s: %d %d", name, first, second);
    }
}

结果:

【讨论】:

    猜你喜欢
    • 2013-05-30
    • 2017-03-16
    • 2010-10-15
    • 2011-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-06
    相关资源
    最近更新 更多