Finally got accept 884ms!!! javascript solution TLE


  • 0
    M

    /**

    var TwoSum = function() {

    this.db = {};
    

    };

    /**

    • Add the number to an internal data structure.
    • @param {number} input
    • @returns {void}
      */
      //O(1)

    TwoSum.prototype.add = function(input) {

    if (this.db[input] === undefined) {
        this.db[input] = 1;
    } else {
        this.db[input] += 1;
    }
    

    };

    /**

    • Find if there exists any pair of numbers which sum is equal to the value.
    • @param {number} val
    • @returns {boolean}
      */
      //O(n)

    TwoSum.prototype.find = function(val) {

    for (var num1 in this.db) {
        var num2 = val - num1;
        if (this.db[num2] !== undefined) {
            if (num1 !== num2 || this.db[num2] > 2) {
                return true;
            }
        }
    }
    return false;
    

    };


  • 0
    M

    /**

    • initialize your data structure here

    • @constructor
      */
      var TwoSum = function() {

      this.myMap = new Map();
      };

    /**

    • Add the number to an internal data structure.

    • @param {number} input

    • @returns {void}
      */
      //O(1)
      TwoSum.prototype.add = function(input) {

      if (this.myMap.has(input)) {
      this.myMap.set(input, this.myMap.get(input)+1)
      } else {
      this.myMap.set(input, 1);
      }
      };

    /**

    • Find if there exists any pair of numbers which sum is equal to the value.

    • @param {number} val

    • @returns {boolean}
      */
      //O(n)
      TwoSum.prototype.find = function(val) {

      for (var num1 of this.myMap.keys()) {
      var num2 = val - num1;
      if (this.myMap.has(num2)) {
      if (num1 !== num2 || this.myMap.get(num1) >= 2) {
      return true;
      }
      }
      }
      return false;
      };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.