给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
======================================================
我的解法
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
n = len(nums)
targetl = [target] * n
temp = [targetl[i] - nums[i] for i in range(n)]
temp1 = -1
for i in range(n):
if temp[i] in nums[i:]:
if (temp[i]==nums[i]) & (temp.count(temp[i])==1):
continue
else:
temp1 = nums.index(temp[i],i+1)
break
if temp1>0:
return [i,temp1]
执行用时
824 ms
参考的两种解法:
#执行通过,耗时缩短一半多,共 652ms。
def twoSum(nums, target):
lens = len(nums)
j=-1
for i in range(1,lens):
temp = nums[:i]
if (target - nums[i]) in temp:
j = temp.index(target - nums[i])
break
if j>=0:
return [j,i]
通过字典的方法,查找效率快很多,执行速度大幅缩短,共 88ms。
def twoSum(nums,target):
hashmap={}
for ind,num in enumerate(nums):
hashmap[num] = ind
for i,num in enuamerate(nums):
j = hashmap.get(target-nums)
if j is not None and i!=j:
return [i,j]
作者:lao-la-rou-yue-jiao-yue-xiang
链接:https://leetcode-cn.com/problems/two-sum/solution/xiao-bai-pythonji-chong-jie-fa-by-lao-la-rou-yue-j/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。