刚开始无脑双重循环,虽然通过了,但是效率太低
看了题解后转用map,效率大幅提高
/** * @param {number[]} nums * @param {number} target * @return {number[]} */ var twoSum = function(nums, target) { let length = nums.length let mp = new Map() nums.forEach((d,i)=>{ mp.set(d,i) }) for(let i=0;i!=length;i++) { let j = mp.get(target-nums[i]) if(j!=undefined && i!=j) return [i,j] } };
来源:https://www.cnblogs.com/selfdef/p/12635700.html