leetcode 算法题170 (简单042) 两数之和 III - 数据结构设计

leetcode 算法题170 (简单042) 两数之和 III - 数据结构设计

  • 题目介绍
设计并实现一个 TwoSum 的类,
使该类需要支持 add 和 find 的操作。
  add 操作 -  对内部数据结构增加一个数。
  find 操作 - 寻找内部数据结构中是否存在一对整数,使得两数之和与给定的数相等。
  • 示例

add(1); add(3); add(5);
find(4) -> true
find(7) -> false

add(3); add(1); add(2);
find(3) -> true
find(6) -> false

  • 解法一
/**
 * 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) {
   let map = this.map;
   if(map[number]) {
     map[number]++;
   } else {
     map[number] = 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) {
    let map = this.map;
    for(let key in map) {
      if(value - parseInt(key) === parseInt(key)) {
       if(map[key] > 1) {
         return true;
       }
      } else {
        if(map[value - parseInt(key)]) {
          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)
 */

执行用时 : 1592 ms, 在所有 JavaScript 提交中击败了11.11%的用户

内存消耗 : 118.2 MB, 在所有 JavaScript 提交中击败了100.00%的用户

  • 解法二
/**
 * Initialize your data structure here.
 */
var TwoSum = function() {
  this.set1 = new  Set();
  this.set2 = new  Set();
};

/**
 * Add the number to an internal data structure.. 
 * @param {number} number
 * @return {void}
 */
TwoSum.prototype.add = function(number) {
  let set1 = this.set1, set2 = this.set2;
  if(set1.has(number)) {
    set2.add(number);
  } else {
    set1.add(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) {
    let set1 = this.set1, set2 = this.set2;
    if(value % 2 === 0) {
      if(set2.has(value / 2)) {
        return true;
      }
    }
    for(let n of set1) {
      if(n !== value - n && set1.has(value - n)) {
        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)
 */

执行用时 : 212 ms, 在所有 JavaScript 提交中击败了88.89%的用户

内存消耗 : 47.3 MB, 在所有 JavaScript 提交中击败了100.00%的用户

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值