170. Two Sum III - Data structure design

Easy

一道easy题一直TLE, tradeoff不会算?Take a look at the input data, there's a lot of "add" and a few "find", so you should make "add" O(1) definitely

class TwoSum {

    HashMap<Integer, Integer> hash;
    /** Initialize your data structure here. */
    public TwoSum() {
        hash = new HashMap<>(); 
    }
    /** Add the number to an internal data structure.. */
    public void add(int number) {
        if(hash.containsKey(number)){
            hash.put(number, hash.get(number) + 1);
        } else {
            hash.put(number, 1);
        }
    }
    /** Find if there exists any pair of numbers which sum is equal to the value. */
    public boolean find(int value) {
        for (Map.Entry<Integer,Integer> entry : hash.entrySet()){
            int i = entry.getKey();
            int j = value - i;
            if (i == j && entry.getValue() >= 2 || (i != j && hash.containsKey(j))){
                return true;
            }
        }
        return false;
    }
}

/**
 * Your TwoSum object will be instantiated and called as such:
 * TwoSum obj = new TwoSum();
 * obj.add(number);
 * boolean param_2 = obj.find(value);
 */
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容