两课总和

时间:2018-08-09 02:24:11

标签: java arrays

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布尔值是如何工作的,或者为什么add void以何种方式以及将其原因放入哈希图中的原因。实际上,该类应该执行的操作是使用add函数将项目添加到哈希图中,然后使用find来确定是否可以使用任何两个整数来累加目标。

1 个答案:

答案 0 :(得分: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 
    }
}