一、题目
提示:算法面试题如下
#给定一个整数数组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]
二、解题思路
1、双循环,暴力解法
使用2次For循环遍历元素和索引
时间复杂度
O(n2)
空间复杂度
O(1)
2、单循环,HashMap解法
- 用 HashMap 存储遍历过的元素和对应的索引。
- 空间换时间,一次循环。
时间复杂度
O(n)
空间复杂度
O(n)
三、HashMap算法代码
1、Powershell实现方式
function TwoSum($nums, $target) {
$hashTable = @{}
for ($i = 0; $i -lt $nums.Count; $i++) {
$complement = $target - $nums[$i]
if ($hashTable.ContainsKey($complement)) {
return @($hashTable[$complement], $i)
}
$hashTable[$nums[$i]] = $i
}
return @()
}
# 示例
$nums = @(2, 7, 11, 15)
$target = 9
$result = TwoSum $nums $target
Write-Output $result
2、Python实现方式
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
num_dict = {}
for i , num in enumerate(nums):
complement = target - num
if complement in num_dict:
return [num_dict[complement], i]
num_dict[num] = i
return []