123456789101112131415161718192021222324252627282930313233343536373839404142 |
- import pytest
- def twoSum(nums, target):
- lens = len(nums)
- j=-1
- for i in range(lens):
- if (target - nums[i]) in nums:
- # 如果num2=num1,且nums中只出现了一次,说明找到是num1本身。
- if (nums.count(target - nums[i]) == 1) & (target - nums[i] == nums[i]):
- continue
- else:
- # index(x,i+1)是从num1后的序列后找num2
- j = nums.index(target - nums[i],i+1)
- break
- if j>0:
- return [i,j]
- else:
- return []
- #
- # def twoSum(nums, target):
- # hashmap={}
- # for ind,num in enumerate(nums):
- # hashmap[num] = ind
- # for i,num in enumerate(nums):
- # j = hashmap.get(target - num)
- # if j is not None and i!=j:
- # return [i,j]
- def test_case_1():
- res = twoSum([2, 3, 1, 5, 8], 6)
- expect = [2, 3]
- assert expect == res
|