leetcode170. 两数之和 III - 数据结构设计
题目描述
链接: leetcode170.
设计一个接收整数流的数据结构,该数据结构支持检查是否存在两数之和等于特定值。
实现 TwoSum 类:
TwoSum() 使用空数组初始化 TwoSum 对象
void add(int number) 向数据结构添加一个数 number
boolean find(int value) 寻找数据结构中是否存在一对整数,使得两数之和与给定的值相等。如果存在,返回 true ;否则,返回 false 。
示例:
输入:
["TwoSum", "add", "add", "add", "find", "find"]
[[], [1], [3], [5], [4], [7]]
输出:
[null, null, null, null, true, false]
解释:
TwoSum twoSum = new TwoSum();
twoSum.add(1); // [] --> [1]
twoSum.add(3); // [1] --> [1,3]
twoSum.add(5); // [1,3] --> [1,3,5]
twoSum.find(4); // 1 + 3 = 4,返回 true
twoSum.find(7); // 没有两个整数加起来等于 7 ,返回 false
题解
哈希表
- java解法
class TwoSum {
Map<Integer, Integer> hashmap;
/** Initialize your data structure here. */
public TwoSum() {
this.hashmap = new HashMap<>();
}
/** Add the number to an internal data structure.. */
public void add(int number) {
hashmap.put(number, hashmap.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 (Map.Entry<Integer, Integer> integerIntegerEntry : hashmap.entrySet()) {
Integer temp = integerIntegerEntry.getKey();
if (hashmap.containsKey(value - temp) && value - temp != temp) {
return true;
}
if (value - temp == temp && hashmap.get(temp) > 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);
*/
- golang解法
type TwoSum struct {
hashMap map[int]int
}
/** Initialize your data structure here. */
func Constructor() TwoSum {
return TwoSum{
hashMap: map[int]int{},
}
}
/** Add the number to an internal data structure.. */
func (this *TwoSum) Add(number int) {
this.hashMap[number]++
}
/** Find if there exists any pair of numbers which sum is equal to the value. */
func (this *TwoSum) Find(value int) bool {
for k, v := range this.hashMap {
_, ok := this.hashMap[value - k]
if ok && value - k != k {
return true
}
if value - k == k && v > 1 {
return true
}
}
return false
}
/**
* Your TwoSum object will be instantiated and called as such:
* obj := Constructor();
* obj.Add(number);
* param_2 := obj.Find(value);
*/