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;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值