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% 의 사용 자 를 격파 하 였 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Rails Turbolinks를 페이지 단위로 비활성화하는 방법원래 Turobolinks란? Turbolinks는 링크를 생성하는 요소인 a 요소의 클릭을 후크로 하고, 이동한 페이지를 Ajax에서 가져옵니다. 그 후, 취득 페이지의 데이터가 천이 전의 페이지와 동일한 것이 있...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.