123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051 |
- import pytest
- # 方法1
- 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 []
- # 方法2
- # def twoSum(nums, target):
- # hashmap={}
- #enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标
- # 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]
- @pytest.mark.parametrize(
- "arr, target, expect",
- [
- ([-2, 3, 1, 5], -1, [0, 2]),
- ([2, 3, 1, 5], 6, [2, 3]),
- ([2, 1, 1, 5, 8], 2, [1, 2]),
- ([2, -1, 1, 5, 8], 0, [1, 2]),
- ([2, 0, 0, 1, -1], 0, [1, 2])
- ]
- )
- def test_cases(arr, target, expect):
- assert twoSum(arr, target) == expect
|