170.Two Sum III - Data structure design

https://leetcode.com/problems/two-sum-iii-data-structure-design/discuss/52005/Trade-off-in-this-problem-should-be-considered

The big data test only have the condition that lots of add and few find. In fact, there has to be one operation’s time complexity is O(n) and the other is O(1), no matter add or find. So clearly there’s trade off when solve this problem, prefer quick find or quick add.

Don’t forget space trade-off.

Storing all possible sum may lead to O(n2) space.

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.put(number, map.getOrDefault(number, 0) + 1);
    }

    /** Find if there exists any pair of numbers which sum is equal to the value. */
    public boolean find(int value) {
        for(Integer i : map.keySet()){
            int j = value - i;
            if(i != j){
                if(map.containsKey(j))
                    return true;
            }
            else{
                if(map.get(i) > 1)
                    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);
 */

results matching ""

    No results matching ""