• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
草莓宝宝乖
博客园    首页    新随笔    联系   管理    订阅  订阅
Two Sum III - Data structure design(leetcode170)

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 }                    

 

posted on 2015-10-13 09:08  草莓宝宝乖  阅读(139)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3