要求:
给定一个整数数组 nums
和一个整数目标值 target
,请你在该数组中找出 和为目标值 target
的那 两个 整数,并返回它们的数组下标。
自己代码:
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(len(nums)):
for j in range(i + 1 , len(nums)):
if nums[i] + nums[j] == target:
# print('[%d,%d]' % (i, j))
# print(f'[{i},{j}]')
return [i,j]
nums = [2, 7, 11, 15]
target = 9
s = Solution()
# print('符合的数组有')
print(s.twoSum(nums, target))
标准答案:
# 方法一:暴力枚举
class Solution:
def twoSum(self, nums, target):
n = len(nums)
for i in range(n):
for j in range(i + 1, n):
if nums[i] + nums[j] == target:
return [i, j]
return []
# 方法二:哈希表
class Solution:
def twoSum(self, nums, target):
hashtable = dict()
for i, num in enumerate(nums):
if target - num in hashtable:
return [hashtable[target - num], i]
hashtable[nums[i]] = i
return []