LeetCode170 两数之和 III - 数据结构设计
题目
解题
解题一:哈希表
// javascript
var TwoSum = function() {
this.map = new Map();
};
/**
* @param {number} number
* @return {void}
*/
TwoSum.prototype.add = function(number) {
this.map.set(number, (this.map.get(number) || 0) + 1);
};
/**
* @param {number} value
* @return {boolean}
*/
TwoSum.prototype.find = function(value) {
for (const x of this.map.keys()) {
const y = value - x;
// 如果 x = y 那要保证 x 至少出现了两次
if (x !== y && this.map.has(y) || x === y && this.map.get(x) > 1) {
return true;
}
}
return false;
};
解题二:排序 + 双指针
查找前要确认已经完成排序,特别注意 is_sorted 标志位 的处理。
// javascript
TwoSum.prototype.add = function(number) {
this.nums.push(number);
this.is_sorted = false;
};
/**
* @param {number} value
* @return {boolean}
*/
TwoSum.prototype.find = function(value) {
if (this.is_sorted === false) {
this.nums.sort((a, b) => a - b);
this.is_sorted = true;
}
let low = 0, high = this.nums.length - 1;
while (low < high) {
const currSum = this.nums[low] + this.nums[high];
if (currSum < value) {
low++;
} else if (currSum > value) {
high--;
} else {
return true;
}
}
return false;
};