💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
#### Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. Example: ~~~ Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]. ~~~ ~~~ var twoSum = function(nums, target) { let arr = [], hash = {}, len = nums.length, t1, index = 0, t2; while (index < len) { t2 = len - index - 1; hash[nums[t2]] = t2; t1 = hash[target - nums[index]]; if (t1 !== undefined && t1 !== index) { arr.push(index) index > t1 ? arr.unshift(t1) : arr.push(t1); break; } hash[nums[index]] = index; index++; } return arr; }; ~~~ ``` /** * @param {number[]} nums * @param {number} target * @return {number[]} */ var twoSum = function(nums, target) { let res=[]; let obj={}; nums.forEach((item,index)=>{ // 如果obj中已存在值为(target-item)键, // 则找到了两个值相加等于target的项,返回索引即可 if(obj.hasOwnProperty(target-item)){ res[1]=index; res[0]=obj[target-item]; return res; } // obj键存数组项的值,值存数组项的索引 obj[item]=index; }) return res; }; ```