给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。
你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
试解:
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
ans = []
for i in range(len(nums)-1):
j = i + 1
while (j) <= (len(nums)-1):
if nums[i] + nums[j] == target:
ans.append(i)
ans.append(j)
return ans
else:
j += 1
简单的数据测试可以通过:
但是对于复杂数组时间会超时:
进行了两次循环时间复杂度为O(N^2)
改进:快速排序算法,从最大最小加和开始和target比较,如果和过大,则缩小最大值;如果和过小,则放大最小值:
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
ans = []
new=nums[:]
new.sort()
i=0 #lable min of nums
j=len(new)-1 #lable max of nums
while i<len(new) and j>0:
if new[i]+new[j] == target:
a=nums.index(new[i])
b=nums.index(new[j],a) #此处避免a=b
ans.append(a)
ans.append(b)
return ans
elif new[i]+new[j] > target:
j-=1
elif new[i]+new[j] < target:
i+=1
测试仍未通过,因为只考虑了target是正值的情况:
这里出错是因为先找到了a=4(nums[4]=-5),按照b=nums.index(new[j],a),只能往后面去找-3,是找不到的,所以会出错,这句就应该改掉了改正:
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
ans = []
new=nums[:]
new.sort()
i=0 #lable min of nums
j=len(new)-1 #lable max of nums
while i<len(new) and j>0:
if new[i]+new[j] == target:
a=nums.index(new[i])
nums[a]='replace' #replace in nums
b=nums.index(new[j])
ans.append(a)
ans.append(b)
return ans
elif new[i]+new[j] > target:
j-=1
elif new[i]+new[j] < target:
i+=1
测试通过。
这样时间复杂度变成快速排序算法的O(nlogn),用了52ms
网上看到可以用enumerate() 函数遍历,enumerate() 函数释义,摘录如下:
描述
enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
Python 2.3. 以上版本可用,2.6 添加 start 参数。
语法
以下是 enumerate() 方法的语法:
enumerate(sequence, [start=0])
参数
- sequence -- 一个序列、迭代器或其他支持迭代对象。
- start -- 下标起始位置。
返回值
返回 enumerate(枚举) 对象。
实例
以下展示了使用 enumerate() 方法的实例:
>>>seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1)) # 小标从 1 开始
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
普通的 for 循环
>>>i = 0
>>> seq = ['one', 'two', 'three']
>>> for element in seq:
... print i, seq[i]
... i +=1
...
0 one
1 two
2 three
for 循环使用 enumerate
>>>seq = ['one', 'two', 'three']
>>> for i, element in enumerate(seq):
... print i, element
...
0 one
1 two
2 three
算法改进如下:
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
result = []
for i, value in enumerate(nums):
if (target - value) in nums[i+1:]:
result.append(nums.index(value))
nums[i]='replace'
result.append(nums.index(target-value))
return result
但是其实变得更慢了哈哈哈哈哈哈,why!1260ms