@(labuladong的算法小抄)[nSum]
leetcode 170. 两数之和 III
题目描述
设计一个类,拥有两个API:
解题思路
参考:labuladong的算法小抄P316
class TwoSum {
HashMap<Integer, Integer> freq = new HashMap<>();
/* 在数据结构中添加一个数number */
public void add(int number) {
/* 记录number的出现次数 */
freq.put(number, freq.getOrDefault(number, 0) + 1);
}
/* 寻找当前数据结构中是否存在两个数的和为value */
public boolean find(int value) {
for (Integer key : freq.keySet()) {
Integer other = value - key;
/* 如果重复 */
if (other == key && freq.get(other) > 1) {
return true;
}
/* 如果不重复 */
if (other != key && freq.containsKey(other)) {
return true;
}
}
return false;
}
}