1、两数之和

1、两数之和

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
你可以按任意顺序返回答案。

示例 1:
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1]

示例 2:
输入:nums = [3,2,4], target = 6
输出:[1,2]

示例 3:
输入:nums = [3,3], target = 6
输出:[0,1]

来源:力扣(LeetCode)
链接:leetcode-cn.com/problems/tw…

1、暴力解法:for for

var twoSum = function(nums, target) {    const length = nums.length    for(let i = 0;i < length; i++) {    for(let j = i + 1;j < length + 1;j++) {            if (nums[i] + nums[j] == target) {            return [i, j]            }        }    }};

2、动态哈希表算法 --推荐

var twoSum = function(nums, target) {    const hashMap = new Map()    // 第一项前无相加项,故先存入哈希表    hashMap.set(nums[0], 0)    const length = nums.length    for (let i = 1; i < length; i++) {    let otherNums = target - nums[i] // 获取        if (hashMap.get(otherNums) != undefined) return [hashMap.get(otherNums), i]        hashMap.set(nums[i], i) // 不匹配的存入哈希表    }};
免责声明:本网信息来自于互联网,目的在于传递更多信息,并不代表本网赞同其观点。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,并请自行核实相关内容。本站不承担此类作品侵权行为的直接责任及连带责任。如若本网有任何内容侵犯您的权益,请及时联系我们,本站将会在24小时内处理完毕。
相关文章
返回顶部