给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
- 自己的想法
拿target减去nums[i],由于不可重复利用元素,就想到给减去的数赋值“inf”,再利用循环。
代码:
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(len(nums)):
less = target - nums[i]
nums[i] = float('inf')
if less in nums:
j = nums.index(less)
return [i, j]
break
ts = Solution()
nums = [2,7,11,15]
target = 9
print(ts.twoSum(nums,target))
结果:
[0,1]
后来看到他人更好的解法
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
l = len(nums)
for a in range(l):
one_unm = nums[a]
other_one = target - one_unm
if other_one in nums:
b = nums.index(other_one)
if a != b:
if a>b:
return [b,a]
return [a,b]
---------------------
作者:XksA
来源:CSDN
原文:https://blog.csdn.net/qq_39241986/article/details/82799897
版权声明:本文为博主原创文章,转载请附上博文链接!
- 他人更好解法
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
l = len(nums)
dict_nums = {nums[i]:i for i in range(l)}
for a in range(l):
one_unm = nums[a]
other_one = target - one_unm
if other_one in dict_nums and a!= dict_nums[other_one]:
return [a,dict_nums[other_one]]
---------------------
作者:XksA
来源:CSDN
原文:https://blog.csdn.net/qq_39241986/article/details/82799897
版权声明:本文为博主原创文章,转载请附上博文链接!
这种方法耗时短的原因是用到了字典。