ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
link: https://leetcode.com/problems/two-sum/description/ > 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]. ``` # JavaScript ```js /** * @param {number[]} nums * @param {number} target * @return {number[]} */ ``` >[danger] runtime: 7056 ms ```js var twoSum = function(nums, target) { for (let i in nums) { for (let j in nums) { if (i !== j && nums[i] + nums[j] === target) { return [parseInt(i), parseInt(j)] } } } return [-1, -1] }; ``` >[danger] runtime: 312 ms ```js var twoSum = function(nums, target) { for (let i = 0; i < nums.length; i++) { for (let j = 0; j < nums.length; j++) { if (i !== j && nums[i] + nums[j] === target) { return [parseInt(i), parseInt(j)] } } } return [-1, -1] }; ``` >[success] runtime: 82 ms ```js var twoSum = function(nums, target) { const dict = {}; for (var i = nums.length; i >= 0 ; i--) { if (dict[nums[i]] !== undefined) { return [dict[nums[i]], i]; } dict[target - nums[i]] = i; } }; ``` >[success] runtime: 86 ms ```js var twoSum = function(nums, target) { var index = {} for(var i = 0,len = nums.length; i < len; i++) { var matchNum = target - nums[i]; if(typeof index[matchNum] === 'number') return [index[matchNum], i] index[nums[i]] = i; } }; ``` > 总结: 字典查询速度特别快,尽量少用`for-in`循环,普通`for`循环速度一般,多级循环会降低执行速度。