two sum III Data structure design

170. two sum III data structure design

题目的原意是设计一个带有Add 和 find 方法的 two sum的类。

question: design and implements 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.

解题思路:可以参照two sum 和 two sum II的方法来些这个类的Add和find的方法。

方法1: 用list来存储所有添加的数值,用hash table存储所有可能的两个数值的和。

写add函数时,每添加一个新的数值,需要遍历在list中所有的数,生成所有可能的数值和,并添加到hash table中。这个方法,add 有O(n) runtime, find 有O(1) runtime. 但需要O(n^2)的space来做存储。

这个方法可以用在使用add操作少的地方。

方法2:将每次加入的数值用binary search的方法来排序,查找的时候用two points的方法来查找。这样add的runtime 是 O(logn), find的runtime是O(n).

方法3:将每次加入的数值用hash table存储。查找的时候,用two sum的方法遍历hash table。这样可以是add的runtime O(1), find的runtime O(n).

public class TwoSum {
    private Map<Integer, Integer> table = new HashMap<>();
    public void add(int input) {
         int count = table.containsKey(input)? table.get(input) : 0;
         table.put(input, count + 1);
    }
    public boolean find(int value) {
       for (Map.Entry<Integer, Integer> entry : table.entrySet()){
            int num = entry.getKey();
            int target = value - num;
            if (target == num) {
               if (entry.getVaule() >= 2) return true;
            } else if (table.containsKey(target)) {
               return true;
            }
       }
       return false;
    }
}

猜你喜欢

转载自blog.csdn.net/BaibuT/article/details/80768228