Two Sum III - Data structure design

题目
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.

答案

class TwoSum {
    Map<Integer, Integer> map; 
    /** Initialize your data structure here. */
    public TwoSum() {
        map = new HashMap<>();
    }
    
    /** Add the number to an internal data structure.. */
    public void add(int number) {
        map.putIfAbsent(number, 0);
        map.put(number, map.get(number) + 1);
    }
    
    /** Find if there exists any pair of numbers which sum is equal to the value. */
    public boolean find(int value) {
        for(Map.Entry<Integer, Integer> e : map.entrySet()) {
            int key = e.getKey();
            int val = e.getValue();
            
            Integer diff_cnt = map.get(value - key);
            if(diff_cnt == null) continue;
            if(value - key == key) {
                if(diff_cnt > 1) return true;
            }
            else {
                return true;
            }
            
        }
        return false;
    }
}

/**
 * Your TwoSum object will be instantiated and called as such:
 * TwoSum obj = new TwoSum();
 * obj.add(number);
 * boolean param_2 = obj.find(value);
 */
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,183评论 0 10
  • Description Design and implement a TwoSum class. It shoul...
    Nancyberry阅读 1,310评论 0 0
  • Design and implement a TwoSum class. It should support th...
    matrxyz阅读 1,351评论 0 0
  • 1.原始模块加载的弊端 全局作用域下容易造成变量冲突 js文件只能按照固定的顺序进行加载 开发人员必须主观解决模块...
    馋中解禅阅读 3,538评论 0 0
  • 毕业答辩结束了,意料之中也在意料之外,成绩是中等,同一个老师,舍友在很认真很努力的修正自己的方案,而我真的太没有把...
    IDgirl阅读 1,243评论 0 0

友情链接更多精彩内容