美文网首页
170. Two Sum III - Data structur

170. Two Sum III - Data structur

作者: jluemmmm | 来源:发表于2021-08-17 10:53 被阅读0次

设计一个接受整数流的数据结构,并检查它是否有一对整数总和为特定值。

  • 时间复杂度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)
 */

相关文章

网友评论

      本文标题:170. Two Sum III - Data structur

      本文链接:https://www.haomeiwen.com/subject/ewzvbltx.html