版权声明:本文为博主原创文章,转载请注明文章出处。 https://blog.csdn.net/qfeung/article/details/88083494
题目
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.
给定一个整数数组nums
和一个目标值target
,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
实例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
Swift 解答
class Solution {
// 用下划线 _ 来代替参数标签, 这样, 在调用函数的时候就不需要写参数标签了
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
// dict 是一个空的 [Int: String] 字典
var dict = [Int: Int]();
// Swift 中遍历数组的方法
for (index, value) in nums.enumerated() {
let otherValue = target - value;
if dict[otherValue] != nil {
return [dict[otherValue]!, index];
} else {
// Swift 中字典对象添加键值对的方式
dict[value] = index;
}
}
return [0, 0];
}
}
Python3 解答
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
hash_map = dict()
for i, value in enumerate(nums):
if target - value in hash_map:
return [i, hash_map[target - value]]
hash_map[value] = i
分析
-
时间复杂度:O(n), 我们只遍历了包含有 n 个元素的列表一次。在表中进行的每次查找只花费 O(1) 的时间。
-
空间复杂度: O(n), 所需的额外空间取决于哈希表中存储的元素数量,该表最多需要存储 n 个元素。