two_sum.py 918 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import pytest
  2. def twoSum(nums, target):
  3. lens = len(nums)
  4. j=-1
  5. for i in range(lens):
  6. if (target - nums[i]) in nums:
  7. # 如果num2=num1,且nums中只出现了一次,说明找到是num1本身。
  8. if (nums.count(target - nums[i]) == 1) & (target - nums[i] == nums[i]):
  9. continue
  10. else:
  11. # index(x,i+1)是从num1后的序列后找num2
  12. j = nums.index(target - nums[i],i+1)
  13. break
  14. if j>0:
  15. return [i,j]
  16. else:
  17. return []
  18. #
  19. # def twoSum(nums, target):
  20. # hashmap={}
  21. # for ind,num in enumerate(nums):
  22. # hashmap[num] = ind
  23. # for i,num in enumerate(nums):
  24. # j = hashmap.get(target - num)
  25. # if j is not None and i!=j:
  26. # return [i,j]
  27. def test_case_1():
  28. res = twoSum([2, 3, 1, 5, 8], 6)
  29. expect = [2, 3]
  30. assert expect == res