0JS实现:数组两数之和算法的两种解决方案(一步一步剖析,很详细)
// 方法一:暴力法
var twoSum = function(nums, target) {
var len = nums.length;
for (var i = 0; i < len; i++) {
for (var j = i + 1; j < len; j++) {
if (nums[i] + nums[j] == target) {
return [i, j];
}
}
}
return [];
};
// 方法二:哈希表
var twoSum = function(nums, target) {
var map = {};
for (var i = 0; i < nums.length; i++) {
var complement = target - nums[i];
if (map[complement] !== undefined) {
return [i, map[complement]];
}
map[nums[i]] = i;
}
return [];
};
评论已关闭