170. Two Sum III - Data structur

2021-08-17  本文已影响0人  jluemmmm

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

/**
 * 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)
 */
上一篇 下一篇

猜你喜欢

热点阅读