170. Two Sum III - Data structure design

Description

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

Solution

HashMap, add time O(1), find time O(n), space O(n)

class TwoSum {
    private Map<Integer, Integer> numToCount;

    /** Initialize your data structure here. */
    public TwoSum() {
        numToCount = new HashMap<>();
    }
    
    /** Add the number to an internal data structure.. */
    public void add(int number) {
        numToCount.put(number, numToCount.getOrDefault(number, 0) + 1);
    }
    
    /** Find if there exists any pair of numbers which sum is equal to the value. */
    public boolean find(int value) {
        for (int num : numToCount.keySet()) {
            int need = value - num;
            
            if (need == num && numToCount.get(need) > 1) {
                return true;
            } else if (need != num && numToCount.containsKey(need)) {
                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);
 */

HashMap + ArrayList, runtime slitely better

事实证明遍历HashMap的keySet是比较慢的,可以用一个额外的List保存所有distinct numbers,然后用来遍历。

Iteration over the collection-views of a LinkedHashMap requires time proportional to the size of the map, regardless of its capacity. Iteration over a HashMap is likely to be more expensive, requiring time proportional to its capacity.

class TwoSum {
    private Map<Integer, Integer> numToCount;
    private List<Integer> list;

    /** Initialize your data structure here. */
    public TwoSum() {
        numToCount = new HashMap<>();
        list = new ArrayList<>();
    }
    
    /** Add the number to an internal data structure.. */
    public void add(int number) {
        if (!numToCount.containsKey(number)) {
            list.add(number);
        }
        numToCount.put(number, numToCount.getOrDefault(number, 0) + 1);
    }
    
    /** Find if there exists any pair of numbers which sum is equal to the value. */
    public boolean find(int value) {
        for (int num : list) {
            int need = value - num;
            
            if (need == num && numToCount.get(need) > 1) {
                return true;
            } else if (need != num && numToCount.containsKey(need)) {
                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);
 */
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容