❤ LeetCode Simple 1-Sum of Two Numbers
1. Topic requirements
Numbers A + B = target
, using target as the summation result, find out the corresponding subscripts of A and B numbers in the array.
When I did it for the first time, I was completely confused, and then I looked at the topic carefully and found that I found two numbers subscripts that match the target and
Solution 1: After reading the solution, it is the first time to brute force the problem with a double-layer for loop [Complexity O(n²)]**
var twoSum = function (nums, target) {
let datas = {
};
for (let i = 0; i < nums.length; i++) {
for (let s = i + 1; s < nums.length; s++) {
if (target==nums[i] + nums[s]) {
return[i,s];
}
}
}
};
After changing the judgment condition [target-nums[i]==nums[s]] the code is optimized
简单粗暴,2遍for循环逐个遍历判断
var twoSum = function (nums, target) {
l
et datas = {
};
for (let i = 0; i < nums.length; i++)
{
for (let s = i + 1; s < nums.length; s++) {
if (target-nums[i] == nums[s])
{
return[i,s];
} } } };
Solution 2
Considering that the hash table uses the sum to subtract one of the numbers to determine whether the other number exists, there is: the subscript of the returned number and the subscript of the difference number; if it does not exist, record the subscript of the current subtracted number, which is convenient for the function Continue to judge and use next time [complexity O(n1)]**
var twoSum = function(nums, target) {
var keys = {
};
for(var i = 0;i < nums.length; i++) {
var diff = target - nums[i];
// 判断差值diff在键值对中是否存在 是则找到匹配数字 数组第二个数字为7,下标为1
// keys[diff]=7,i=2
if(!isNaN(keys[diff])) {
// 返回减去的数字下标和差值数字的下标
return [keys[diff], i];
}
// 未出现匹配值 将数字存入键值对中以备后续判断
// 当前数字假设为第三个 nums[i]=7,keys[7]=1 i就是判断数字的下标 建立key值 方便下次使用
// 若是7的差值不存在,当前数字7的下标就是1,将1记录为7的下标
keys[nums[i]] = i;
}
};