弟中弟的Leetcode总结——数组类(四)
题目描述
Two Sum
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.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
思路——Naive Solution
看到这题的第一反应是两重循环判断结束,时间复杂度是O(n^2)。然而提交后发现超时了。。。因此需要另寻他法。
思路——Improved Solution
思考了一下怎样可以降低时间复杂度。可以将数组进行排序。但是最后要输出的是原来的下标,因此将数组复制一下。然后再设置两个指针,一个指向最前,一个指向最后,开始的时候相加的和一定是大于等于target的值的,因此当后面的指针不断向前,直到小于等于的时候停止,再判断如果和小于target,则移动前面的指针,如果和等于target,直接输出原有的下标即可。
有一个需要注意的地方就是在寻找下标的时候,如果是两个相同的值相加等于target,例如输入[3,3] 6,那么在得到两个值为3后需要判断一下下标是否正确。
代码(py3)
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
leng=len(nums)
#复制数组作为下标参考
nu=nums[:]
nums.sort();
for i in range(leng):
j=leng-1
while(nums[i]+nums[j]>target):
j=j-1
if(nums[i]+nums[j]==target):
x=nu.index(nums[i])
y=nu.index(nums[j])
if(x==y):
nu[x]=1000000
y=nu.index(nums[j])
return [min(x,y),max(x,y)]