✊ 作者: 七弦 ✊不积跬步,无以至千里;不积小流,无以成江海。 ✊ 时间:2021.07.12 ✊ 题目来源: 力扣 - 1
1. 题目说明
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 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]
2. 题目解决
2.1 暴力枚举法
时间复杂度:O(n2) 空间复杂度:O(1)
var twoSum = function(nums, target) {for (let i = 0; i < nums.length; i++) {const x = nums[i];for (let j = i + 1; j < nums.length; j++) {if (nums[j] == target - x) {return [i, j]}}}return []};
2.2 静态hash表
时间复杂度:O(n) 空间复杂度:O(n) 空间换时间
var twoSum = function(nums, target) {const map = new Map()nums.forEach((num, i) => map.set(num, i))for (let i = 0; i < nums.length; i++) {const x = nums[i];if (map.has(target - x)) {const index = map.get(target - x)if (i != index) return [i, index]}}return []};
2.3 动态hash表
时间复杂度:O(n) 空间复杂度:O(n) 空间换时间
var twoSum = function(nums, target) {const map = new Map()for (let i = 0; i < nums.length; i++) {const x = nums[i];if (map.has(target - x)) {const index = map.get(target - x)return [i, index]}map.set(x, i)}return []};
