two_sum.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import pytest
  2. # 方法1
  3. def twoSum(nums, target):
  4. lens = len(nums)
  5. j=-1
  6. for i in range(lens):
  7. if (target - nums[i]) in nums:
  8. # 如果num2=num1,且nums中只出现了一次,说明找到是num1本身
  9. if (nums.count(target - nums[i]) == 1) & (target - nums[i] == nums[i]):
  10. continue
  11. else:
  12. # index(x,i+1)是从num1后的序列找num2
  13. j = nums.index(target - nums[i], i+1)
  14. break
  15. if j > 0:
  16. return [i, j]
  17. else:
  18. return []
  19. # 方法2
  20. # def twoSum(nums, target):
  21. # hashmap={}
  22. #enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标
  23. # for ind,num in enumerate(nums):
  24. # hashmap[num] = ind
  25. # for i,num in enumerate(nums):
  26. # j = hashmap.get(target - num)
  27. # if j is not None and i!=j:
  28. # return [i,j]
  29. @pytest.mark.parametrize(
  30. "arr, target, expect",
  31. [
  32. ([-2, 3, 1, 5], -1, [0, 2]),
  33. ([2, 3, 1, 5], 6, [2, 3]),
  34. ([2, 1, 1, 5, 8], 2, [1, 2]),
  35. ([2, -1, 1, 5, 8], 0, [1, 2]),
  36. ([2, 0, 0, 1, -1], 0, [1, 2])
  37. ]
  38. )
  39. def test_cases(arr, target, expect):
  40. assert twoSum(arr, target) == expect