# 170 Two Sum III

設計一個TwoSum class,支援add和find operation。

  • Idea: The original problem is saving all (value - number) in a HashMap, but now the value is given when calling find. The simplest way would be save all number in a list, when a value is given, search the list and generate HashMap.
  • Code: 我後來用HashSet而不用HashMap,因為發現不需要key跟value,把value存進去就可以了~這樣可以少存一點東西。
public class TwoSum {
    /*
    original problem is saving all value - number in a HashMap
    but now the value is given when calling find.
    simplest way would be save all number in a list,
    when a value is given, search the list and generate hashmap
    */
    List<Integer> list;
    /** Initialize your data structure here. */
    public TwoSum() {
        list = new ArrayList<>();
    }

    /** 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) {
        Set<Integer> set = new HashSet<>();
        for(int i=0; i<list.size(); i++){
            if(set.contains(value - list.get(i))){
                return true;
            }
            set.add(list.get(i));
        }
        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);
 */

results matching ""

    No results matching ""