Two Sum III - Data structure design

来源:互联网 发布:浏览器不能调用java 编辑:程序博客网 时间:2024/05/16 07:54

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
思路1,用list来装数据,find的时候,用hashmap的key去存target-number,类似two sum来判断;

public class TwoSum {    private List<Integer> list = new ArrayList<Integer>();    // Add the number to an internal data structure.public void add(int number) {    list.add(number);}    // Find if there exists any pair of numbers which sum is equal to the value.public boolean find(int value) {    HashMap<Integer, Integer> hashmap = new HashMap<Integer, Integer>();    for(int i=0; i<list.size(); i++){        if(hashmap.containsKey(list.get(i))){            return true;        } else {            hashmap.put(value-list.get(i), list.get(i));        }    }    return false;}}

思路2:用hashmap来统计频率,然后用这个hashmap的keySet来判断,如果两者不相等,找到了,那么return true。如果两者相等,就判断收集起来的个数是否>=2.

public class TwoSum {       private HashMap<Integer, Integer> hashmap;    public TwoSum(){        hashmap = new HashMap<Integer, Integer>();    }    public void add(int number) {    Integer k = hashmap.get(number);    if(k == null){        hashmap.put(number, 1);    } else {        hashmap.put(number, k+1);    }}    // Find if there exists any pair of numbers which sum is equal to the value.public boolean find(int value) {    for(Integer i: hashmap.keySet()){        if(hashmap.containsKey(value-i)){            if(value != 2*i || (value == 2*i && hashmap.get(i) >=2)){                return true;            }          }    }    return false;}}



0 0