Python3实现:
- 暴力解法:时间复杂度n2,空间复杂度1
python
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
if not nums and len(nums) > 2:
raise Exception("输入数据格式有误!")
length = len(nums)
for i, num in enumerate(nums):
for j in range(i + 1, length):
if nums[i] + nums[j] == target:
return [i, j]
return []
关注点:range为左闭右开,enumerate可以设定索引开始值。
- hash方法:时间复杂度n,空间复杂度n
python
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
if not nums and len(nums) > 2:
raise Exception("输入数据格式有误!")
des_dict = {}
for i in range(len(nums)):
dif = target - nums[i]
if dif in des_dict.keys():
return [des_dict[dif], i]
des_dict[nums[i]] = i
return []
这种算是哈希表的变形实现,使用了字典当作hash表。