最简单的第一题,想要有好的时间空间复杂度也是挺难得

    1. #暴力解1 用了两层for循环
    2. def twoSum(self, nums: list[int], target: int) -> list[int]:
    3. for i in range(len(nums)-1):
    4. for j in range(i+1, len(nums)): #有个问题,最后两个元素不会被遍历
    5. if nums[i]+nums[j] == target:
    6. return [i, j]
    7. #暴力解2 使用了列表内置的count 和 index
    8. class Solution:
    9. def twoSum(self, nums: List[int], target: int) -> List[int]:
    10. for i in range(len(nums)-1):
    11. if target-nums[i] in nums:
    12. if nums.count(target-nums[i]) == 1 and 2*nums[i] == target: #说明只有一个
    13. continue
    14. j = nums.index(target-nums[i], i+1, len(nums))
    15. return [i, j]
    16. return []
    17. #暴力解3 优化了方法2 优化了索引
    18. class Solution:
    19. def twoSum(self, nums: List[int], target: int) -> List[int]:
    20. for i in range(len(nums)-1):
    21. if target-nums[i] in nums[i+1:]:
    22. j = nums.index(target-nums[i], i+1, len(nums))
    23. return [i, j]
    24. return []
    25. #解4 采用了字典模仿哈希
    26. class Solution:
    27. def twoSum(self, nums: List[int], target: int) -> List[int]:
    28. dic = {}
    29. for i,n in enumerate(nums):
    30. cp = target - n
    31. if cp in dic:
    32. return [dic[cp], i]
    33. else:
    34. dic[n] = i #真的绝,用值作为键,用索引作为值,直接访问