给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:两层循环暴力 O(n^2)
用字典暂存,因为字典自带Hash索引,O(n)
Python 自己写的:
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
mid_dict = {}
for index, one in enumerate(nums):
if one in mid_dict:
mid = [mid_dict[one]] # 这里是为了防止出现诸如 [3, 3] 6 需要返回[0, 1]的情况
mid.append(index)
mid_dict[one] = mid
else:
mid_dict[one] = index
if not target % 2 and target / 2 in mid_dict and type(mid_dict[target/2]) != int:
return mid_dict[target / 2][:2]
for k, v in mid_dict.items():
if target - k in mid_dict and mid_dict[target - k] != v:
return sorted([v, mid_dict[target - k]])
return []
暴力
class Solution:
# 暴力
def twoSum(self, nums: List[int], target: int) -> List[int]:
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
简洁写法:
class Solution:
# 字典
def twoSum(self, nums: List[int], target: int) -> List[int]:
_dict = {}
for i, m in enumerate(nums):
_dict[m] = i
for i, m in enumerate(nums):
j = _dict.get(target - m)
# 若出现重复的元素,字典里保存的是下标较大的。所以要用i!=j判断一下这种特殊情况。 如[3, 3] 6 需要返回[0, 1]
if j is not None and i != j:
return [i, j]
或
class Solution:
# 一遍字典模拟Hash
def twoSum(self, nums: List[int], target: int) -> List[int]:
_dict = {}
for i, m in enumerate(nums):
if _dict.get(target - m) is not None:
return [_dict.get(target - m), i]
_dict[m] = i