[leetcode] 170. Two Sum III – Data structure design

来源:互联网 发布:卖家赠送的淘宝运费险 编辑:程序博客网 时间:2024/06/12 18:48

题目

Design and implement a TwoSum class. It should support the following operations: add and find.

add - Add the number to an internal data structure.
find - Find if there exists any pair of numbers which sum is equal to the value.

For example,

add(1);
add(3);
add(5);
find(4) -> true
find(7) -> false

思路

Since the desired class need add and get operations, HashMap is a good option for this purpose.

代码

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;    }}
0 0
原创粉丝点击