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%的用户