给定一个整数数组 nums
和一个目标值 target
,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
解:
"""
第一次:两遍遍历,外层循环从i到len(nums),内层循环从i+1到len(nums),如果下标i和下标j未出现过,且满足num[i]+num[j]=target,则保存i,j,在本地运行是可以的,但在LeetCode上显示运行超时
"""
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
result = []
for i in range (len(nums)):
for j in range (i + 1, len(nums)):
if i not in result and j not in result:
if nums[j] == target - nums[i]:
result.append(i)
result.append(j)
return result"""
"""
"""
第二次:思路与第一次相同,加了一些break语句,时间上稍微提高一点,通过了,注意在判断时,先写不满足条件的语句,使其break。
"""
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
result = []
for i in range (len(nums)):
if i in result:
break
else:
for j in range (i + 1, len(nums)):
if j in result:
break
else:
if nums[j] == target - nums[i]:
result.append(i)
result.append(j)
return result"""
Runtime: 6044 ms, faster than 5.99% of Python online submissions for Two Sum.
Memory Usage: 12.6 MB, less than 5.29% of Python online submissions for Two Sum.
"""
"""
第三次:遍历一遍nums,判断每个num与taget的差是否在nums中,且差的index不能与num的index相同,同时满足num的index与差的index都是第一次出现。
学会使用enumerate函数及list类型的extend函数
"""
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
result = []
for index, num in enumerate(nums):
if (target - num) in nums and index != nums.index(target - num) and index not in result and nums.index(target - num) not in result:
result.extend((index, nums.index(target - num)))
return result"""
Runtime: 1908 ms, faster than 31.93% of Python online submissions for Two Sum.
Memory Usage: 12.5 MB, less than 5.56% of Python online submissions for Two Sum.
"""
以上三个都可以实现nums中存在多组num,其和为target。