1. 两数之和
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出和为目标值target的那两个整数,
并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
// 思路就是for循环比较
var twoSum = function(nums, target) {
for (let index = 0; index < nums.length; index++) {
for (let childIndex = 0; childIndex < nums.length; childIndex++) {
if(childIndex > index){
if(nums[index] + nums[childIndex] == target){
return [index,childIndex]
}
}
}
}
return []
};
由上面的结果可以看出,两个for循环的好像不是最好的解决方案。那就看看下面的这个思路
基于上面的双循环的优化考虑,主要想要降低时间复杂度
采用了一次循环+hash结构
hash结构是数据nums的值和下标的一一对应
我们用target减去数组中的每一个值,结果肯定是数组中的某一个值,为了减少计算量,每次循环,先判断hash结构中
是否存在 target 减去当前循环的值的结果,这样可以最大程度减少计算时间
var twoSum = function (nums, target) {
let hash = {};
for (let i = 0; i < nums.length; i++) {
if (hash[target - nums[i]] !== undefined) {
return [i, hash[target - nums[i]]];
}
hash[nums[i]] = i;
}
return [];
};
这样的结果是不是看着更舒服一点,有一点是需要注意的:每次同样的代码执行多次 结果可能不一样,我们不追求100%, 但是要注意不同思路的转变带来的不同效果