170. Two Sum III - Data structure design

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

Solution1:Hashtable find再去遍历找

Add O(1) find O(N)

Solution2:Hashset add先遍历算好sum

Add O(N) find O(1)

Solution1 Code:

public class TwoSum {
    Map<Integer,Integer> map;
    
    TwoSum() {
        map = new HashMap<Integer,Integer>();
    }
    // Add the number to an internal data structure.
    public void add(int number) {
        if(map.containsKey(number)) {
            map.put(number, 2);
        }else {
            map.put(number, 1);
        }
    }

    // Find if there exists any pair of numbers which sum is equal to the value.
    public boolean find(int value) {
        Iterator<Integer> iter = map.keySet().iterator();
        while(iter.hasNext()) {
            int num1 = iter.next();
            int num2 = value - num1;
            if(map.containsKey(num2)){
                if(num1 != num2 || map.get(num2) == 2){
                    return true;
                }
            }
        }
        return false;
    }
}

Solution2 Code:

public class TwoSum {
    Set<Integer> sum;
    Set<Integer> num;
        
    TwoSum(){
        sum = new HashSet<Integer>();
        num = new HashSet<Integer>();
    }
    // Add the number to an internal data structure.
    public void add(int number) {
        if(num.contains(number)) {
            sum.add(number * 2);
        } else {
            Iterator<Integer> iter = num.iterator();
            while(iter.hasNext()){
                sum.add(iter.next() + number);
            }
            num.add(number);
        }
    }
    
    // Find if there exists any pair of numbers which sum is equal to the value.
    public boolean find(int value) {
        return sum.contains(value);
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容