问题
https://leetcode.com/problems/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 sameelement twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
解析
题目给定一个int数组和target,找到两数之和=target,返回其下标(从0开始,且index1<index2)
一:暴力法
两层循环暴力求解,能AC,时间性能5%
时间,空间
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j]
return []
二:夹逼法
考虑到排序有可能降低时间开销,然后前后夹逼,使用贪心的思路去搜索:首尾之和>target,则尾部左移;首尾之和<target,则头部右移。
排序会丢失原始下标,必须存储。
时间,空间
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
//构造带原始index的元组,排序
numPairs = []
for i in range(len(nums)):
numPairs.append((nums[i], i))
numPairs = sorted(numPairs, key = lambda x:x[0], reverse=False)
//前后夹逼搜索
start, end = 0, len(numPairs) - 1
while start < end:
if numPairs[start][0] + numPairs[end][0] > target:
end -= 1
elif numPairs[start][0] + numPairs[end][0] < target:
start += 1
else:
ret = [numPairs[start][1], numPairs[end][1]]
ret.sort()
return ret
return []
三:字典查找
求两数之和=target,即遍历数组元素n时,在剩余元素中查找target-n的存在性,字典可破:一边插入字典,一边查找数差
时间,空间
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
numDict = {}
for index in range(0, len(nums)):
if target - nums[index] in numDict:
return [numDict[target - nums[index]], index]
else:
numDict[nums[index]] = index
return []