Easy
一道easy题一直TLE, tradeoff不会算?Take a look at the input data, there's a lot of "add" and a few "find", so you should make "add" O(1) definitely
class TwoSum {
HashMap<Integer, Integer> hash;
/** Initialize your data structure here. */
public TwoSum() {
hash = new HashMap<>();
}
/** Add the number to an internal data structure.. */
public void add(int number) {
if(hash.containsKey(number)){
hash.put(number, hash.get(number) + 1);
} else {
hash.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 : hash.entrySet()){
int i = entry.getKey();
int j = value - i;
if (i == j && entry.getValue() >= 2 || (i != j && hash.containsKey(j))){
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);
*/