// 几年后再抄了抄九章模板,java8了
// <num, count>
Map<Integer, Integer> storage = new HashMap<>();
public void add(int number) {
storage.put(number, storage.getOrDefault(number, 0) + 1);
}
public boolean find(int value) {
for (Integer num : storage.keySet()) {
int diff = value - num;
int countRequired = (diff == num) ? 2 : 1;
if (storage.getOrDefault(diff, 0) >= countRequired) {
return true;
}
}
return false;
}
public class TwoSum {
HashMap<Integer, Integer> storage = new HashMap<>();
// Add the number to an internal data structure.
public void add(int number) {
if (storage.containsKey(number)) {
storage.put(number, storage.get(number) + 1);
} else {
storage.put(number, 1);
}
// Java 8 : hm.put(number, hm.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 (HashMap.Entry<Integer, Integer> elem : storage.entrySet()) {
int diff = value - elem.getKey();
if (storage.containsKey(diff)) {
if (diff == elem.getKey() && storage.get(diff) > 1) {
return true;
} else if (diff != elem.getKey()) {
return true;
}
}
}
return false;
}
}