170. Two Sum III - Data structure design

Design and implement a TwoSum class. It should support the following operations:addandfind.
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

呵呵呵奇葩了, 这个也是各种不过, 想找个完美解决方案,就去看讨论区别人的代码, 怎么都不满意, 突然发现一个我想要的代码, 心里一阵窃喜, 结果你猜这么着。那个代码发布者是我自己啊!!!尼玛!!摔键盘, 砸鼠标!

     HashMap<Integer, Integer> map = new HashMap<>(); 
      public void add(int number) {
            map.put(number, map.getOrDefault(number,0) + 1);
      } 
      public boolean find(int value) {
            Set<Integer> keyset = map.keySet();
            for(Integer key: keyset){
                   if(value == key * 2 && map.get(key) > 1
                      || value != key * 2 && map.containsKey(value - key) ){
                            return true;
                   }
             }
            return false;
     }

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容