给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
#个人解答:
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(len(nums)-1):
for j in range(len(nums)-i-1):
if nums[i]+nums[i+j+1] == target:
return [i,i+j+1]
其他解答:
解法一:暴力循环
class Solution(object):
def twoSum(self, sums,target):
size = len(nums)
for i, m in enumerate(nums):
j = i + 1
while j < size:
if target == (m + nums[j]):
return [i, j]
else:
# print(i, j, m + _n, " didn't match!")
j += 1
对于给定的target,遍历数组 时间复杂度O(n), 查找target == m+ n的元素,时间复杂度 O(n) 因为时间复杂度为 O(n^2) 遍历过程,未使用数据结构存储,故空间复杂度为O(1) 耗时 60ms
解法二:字典模拟Hash
class Solution(object):
def twoSum(self, sums,target):
_dict = {}
for i, m in enumerate(nums):
_dict[m] = i
for i, m in enumerate(nums):
j = _dict.get(target - m)
if j is not None and i != j:
return [i, j]
时间复杂度为O(n) 空间复杂度为O(n) 执行时间 52 ms
解法三:一遍字典模拟Hash
扫描二维码关注公众号,回复:
8499272 查看本文章
class Solution(object):
def twoSum(self, sums,target):
_dict = {}
for i, m in enumerate(nums):
if _dict.get(target - m) is not None:
return [i, _dict.get(target - m)]
_dict[m] = i
时间复杂度为O(n) 空间复杂度为O(n) 执行时间 46 ms。
map()函数:
将list中的string批量转化成int/float
a = ["1", "2", "3.1"]
b = list(map(eval, a))
a1 = ["1","2","3"]
b1 = list(map(int, a1))
print(b)
print(b1)
print(list(map(int, a))
输出:
[1, 2, 3.1]
[1, 2, 3]
ValueError: invalid literal for int() with base 10: '3.1'
参考链接:https://leetcode-cn.com/problems/two-sum/solution/python3-san-chong-jie-fa-by-smallhi/