Two Sum III - Data structure design
Description
null
Solution(javascript)
/**
* Initialize your data structure here.
*/
var TwoSum = function() {
this.map = {}
};
/**
* Add the number to an internal data structure..
* @param {number} number
* @return {void}
*/
TwoSum.prototype.add = function(number) {
this.map[number] = (this.map[number] || 0) + 1
};
/**
* Find if there exists any pair of numbers which sum is equal to the value.
* @param {number} value
* @return {boolean}
*/
TwoSum.prototype.find = function(value) {
return Object.keys(this.map).some(key => {
const num1 = Number(key)
const num2 = value - num1
if(num1===num2) {
if(this.map[num1] >= 2) {
return true
}
} else if(this.map[num2] >= 1) {
return true
}
return false
})
};
/**
* Your TwoSum object will be instantiated and called as such:
* var obj = new TwoSum()
* obj.add(number)
* var param_2 = obj.find(value)
*/