0
public class TwoSum {
private HashMap<Integer, Integer> elements = new HashMap<Integer, Integer>();

public void add(int number) {
    if (elements.containsKey(number)) {
        elements.put(number, elements.get(number) + 1);
    } else {
        elements.put(number, 1);
    }
}

public boolean find(int value) {
    for (Integer i : elements.keySet()) {
        int target = value - i;
        if (elements.containsKey(target)) {
            if (i == target && elements.get(target) < 2) {
                continue;
            }
            return true;
        }
    }
    return false;
}
}

我不确定该类如何能够获取哈希图中的数字并告诉我们是否可以将 2 个数字相加以创建另一个数字。具体来说,我不明白 find boolean 是如何工作的,或者为什么 add void 会以它的方式将数字放入哈希图中,以及出于什么原因。实际上,这个类应该做的是使用 add 函数将项目添加到哈希映射中,然后使用 find 来确定是否可以使用任何两个整数来添加到目标。

4

1 回答 1

1

请参阅下面代码中的注释。

public class TwoSum {
    // create a hashmap to contain the NUMBER added and the COUNT of that number
    private HashMap<Integer, Integer> elements = new HashMap<Integer, Integer>();

    public void add(int number) {
        // does the hashmap have the NUMBER as a key
        if (elements.containsKey(number)) {
            // get the COUNT of the NUMBER and increment it by 1
            // and update the hashmap
            elements.put(number, elements.get(number) + 1);
        } else {
            // the NUMBER doesn't exist in the hashmap,
            // so add it and set the COUNT to 1
            elements.put(number, 1);
        }
    }

    public boolean find(int value) {
        // Loop through the NUMBERS (which are keys in the hashmap
        for (Integer i : elements.keySet()) {
            // subtract the NUMBER (i) from the VALUE then
            // all we have to do is look for the TARGET in the hashmap
            int target = value - i;
            // start looking for the TARGET
            if (elements.containsKey(target)) {
                // If we made it here, we found a match
                // if I == TARGET, then there has to be a COUNT of at least 2
                // for example if VALUE = 6 and I = 3 then TARGET also = 3
                // so the COUNT of 3s in the hashmap has to be at least 2
                // if the COUNT is not >= 2 then we jump to the next I
                if (i == target && elements.get(target) < 2) {
                    continue; // jump to next I
                }
                return true; // we found a match to TARGET so we can exit
            }
        }
        return false; // no matches for TARGET 
    }
}
于 2018-08-09T03:03:49.340 回答