Two Sum III - Data structure design

来源:互联网 发布:淘宝购物车流程图 编辑:程序博客网 时间:2024/05/29 08:59

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) -> truefind(7) -> false

Show Company Tags
Show Tags
Show Similar Problems

思路是通过一个hasmap保存一个数字出现的次数,如果sum的值正好是元素的两倍时要能够保证这个元素出现两次才可以。

代码:

HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();    // Add the number to an internal data structure.public void add(int number) {    if(map.containsKey(number)){        map.put(number, map.get(number)+1);    }else{        map.put(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> entry: map.entrySet()){        int item = entry.getKey();        if(map.containsKey(value - item)){            if(item == (value - item)){                if(entry.getValue()>1) return true;            }else{                return true;            }        }    }    return false;}


0 0