170. Two Sum III - Data structur
2021-08-17 本文已影响0人
jluemmmm
设计一个接受整数流的数据结构,并检查它是否有一对整数总和为特定值。
- 时间复杂度O(N),空间复杂度O(N)
- Runtime: 1820 ms, faster than 15.24%
- Memory Usage: 79.4 MB, less than 31.43%
/**
* Initialize your data structure here.
*/
var TwoSum = function() {
this.nums = [];
};
/**
* Add the number to an internal data structure..
* @param {number} number
* @return {void}
*/
TwoSum.prototype.add = function(number) {
this.nums.push(number);
};
/**
* 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) {
const hash = [];
for (let num of this.nums) {
if (hash[value - num]) return true;
else hash[num] = 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)
*/