Two Sum
Given an array of integers nums
and an integer target
, return indices of the two numbers such that they add up to target
.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Example:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation:
Because nums[0] + nums[1] == 9, we return [0, 1]
My solution
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
length = len(nums) - 1
index = 0
answer_list = []
for num_first in nums:
while length > -1:
if (num_first + nums[length] == target) and (index != length):
answer_list.append(index)
answer_list.append(length)
break
length -= 1
if len(answer_list) != 0:
break
else:
index += 1
length = len(nums) - 1
return answer_list
Best solution
def twoSum(self, nums, target):
hash_map = {}
for i in range(len(nums)):
if target - nums[i] in hash_map:
return [hash_map[target - nums[i]], i]
else:
hash_map[nums[i]] = i
# 这个算法使用了哈希表来存储已经遍历过的数字及其索引,
# 以便快速查找目标值减去当前数字的差值是否在数组中。
# 时间复杂度为 O(n)。
在 Python 中,hash_map 通常指的是字典(dictionary)类型。字典是一种可变容器模型,可以存储任意类型的键值对。字典中的键必须是唯一的,但值则不必。
# 创建一个空字典
my_dict = {}
# 向字典中添加键值对
my_dict['key1'] = 'value1'
my_dict['key2'] = 'value2'
# 访问字典中的值
print(my_dict['key1']) # 输出 'value1'
# 删除字典中的键值对
del my_dict['key1']
# 检查键是否在字典中
if 'key1' in my_dict:
print('Key found')
else:
print('Key not found') # 输出 'Key not found'
您可以使用 in 关键字来检查某个键是否在字典中。您还可以使用 del 关键字来删除字典中的某个键值对。
人生便是艺术。