Two Sum III - Data structure design(leetcode170)

本文介绍了一个名为TwoSum的类的设计与实现方法,该类支持add和find两种操作。通过使用哈希表来存储输入数据,使得find操作能够在O(n)的时间复杂度内完成。文章还特别注意了如何正确处理重复元素。

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

A simpler approach is to store each input into a hash table with the input as key and its count as value. To find if a pair sum exists, just iterate through the hash table in O(n) runtime. Make sure you are able to handle duplicates correctly. 

 

 1 public class TwoSum{
 2     //Firstly, we create a hashmap
 3     Map<Integer, Integer> hm = new HashMap<>();
 4 
 5     public void add(int number){
 6         int count = hm.containsKey(number) ? hm.get(number): 0;
 7         hm.put(number, count +1);
 8    }
 9 
10    public boolean find(int value){
11         //The Map.Entry interface enables you to work with a map entry
12         for(Map.Entry<Integer, Integer> entry: hm.entrySet()){
13             int num = entry.getKey();
14             int r = value - num;
15             if(r == num){
16                 // For duplicates, ensure there are at least two individual numbers
17                 if(entry.getValue() >= 2) return true;
18              }else if(hm.containsKey(r)){
19                 return true;
20             }
21         }
22         return false;
23   }
24 }                    

 

转载于:https://www.cnblogs.com/caomeibaobaoguai/p/4873488.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值