题目:
'''
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.'''
1. 最开始的写法:
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
if len(nums) <1 :
return false
for i in range(len(nums)):
temp=target-nums[i]
if temp in nums.index
while j
大部分例子都能通过,有一个出现了如下图所示的提示:
2. 利用index改写为:
class Solution:
def twoSum(self, nums, target):
if len(nums) <1 :
return false
for i in range(len(nums)):
temp=target-nums[i]
if temp in nums:
if i!=nums.index(temp):
return i,nums.index(temp)
3. 利用enumerate()来改写:
class Solution:
def twoSum(self, num, target):
d = dict()
for index, number in enumerate(num):
try:
return ((d[target-number]+1, index+1))
except:
d[number] = index
看到有加了try的,感觉这样很好,借鉴一下。
enumerate(sequence, [start=0])
sequence,序列或迭代对象等
start 下标起始位置
返回值:返回枚举对象,
>>> sq=['one','two','three']
>>> for index,element in enumerate(sq):
print(index,sq[index])
0 one
1 two
2 three
>>>
4.
class Solution:
# @return a tuple, (index1, index2)
# 8:42
def twoSum(self, num, target):
map = {}
for i in range(len(num)):
if num[i] not in map:
map[target - num[i]] = i + 1
else:
return map[num[i]], i + 1
return -1, -1
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有