Easy
这次写得没有只用一个hashMap方法节省空间,记住这道题最优化的解法就是只用一个hashMap. 而且这道题很特别的是遍历到了 for (Map.Entry<Integer, Integer> entry : map.entrySet())
entrySet()
class TwoSum {
List<Integer> list;
/** Initialize your data structure here. */
public TwoSum() {
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) {
Collections.sort(list);
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < list.size(); i++){
if (map.containsKey(value - list.get(i))){
return true;
}
map.put(list.get(i), 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);
*/