【发布时间】:2019-03-23 00:50:17
【问题描述】:
我对twoSum问题的三个解决方案
给定所有整数数组,返回两个数字的索引,使它们相加为特定目标。
您可以假设每个输入都恰好有一个解决方案,并且您不能两次使用 same 元素。
示例:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
一是操作数据结构
class Solution1(): #Manipulate Data
def twoSum(self, nums: List[int], target: int) -> List[List[int]]:
nums_d = {}
couples = []
#O(n)
for i in range(len(nums)):
nums_d.setdefault(nums[i], []).append(i)
for i in range(len(nums)):
complement = target - nums[i]
nums_d[nums[i]].pop(0) #remove the fixer
result = nums_d.get(complement)#hash table to search
#if j is not Nne and j is not empty.
if result: #if exits, it should be [j]
couples.append([nums[i], complement])
return couples
其次是多条件检查
class Solution2: #Double Pass Approach
def twoSum(self, nums, target) -> List[List[int]]:
"""
:type nums: List[int]
:type target: int
"""
if len(nums) < 2:
return []
couples = []
nums_d:dict = {}
for i in range(len(nums)):
#nums_d.setdefault(nums[i], []).append(i)
nums_d[nums[i]] = i
for i in range(len(nums)):
complement = target - nums[i]
# nums_d[nums[i]].pop(0) #remove the fixer
if nums_d.get(complement) != None and nums_d.get(complement) != i:
couples.append([nums[i], complement])
return couples
第三只操作索引
class Solution: 3#Single Pass Approach
def twoSum(self, nums, target) -> List[List[int]]:
"""
:type nums: List[int]
:type target: int
"""
nums_d:dict = {}
couples = []
if len(nums) < 2:
return []
for i in range(len(nums)):
complement = target - nums[i]
logging.debug(f"complement: {complement}")
logging.debug(f"Check: {nums_d.get(complement)}")
if nums_d.get(complement) != None:
# couples.append([i, nums_d.get(complement)])
couples.append([nums[i], complement])
nums_d[nums[i]] = i
logging.debug(f"nums_d: {nums_d}")
return couples
还有我的测试用例
class TestCase(unittest.TestCase):
# logging.debug("Class TestCase started.")
"""
Test for 'twoSum.py'
"""
def setUp(self):
self.solution = Solution1()
self.solution2 = Solution2()
self.solution3 = Solution3()
def test_two_sum3(self):
#random is present
target = 30
nums = random.sample(range(20), k=20)
print(f"\ntarget: {target} \nnums: {nums}")
#Input no-replacement nums
print('Solution Length:', len(self.solution.twoSum(nums, target)))
print('result:', self.solution.twoSum(nums, target))
print('Solution2 Length:', len(self.solution2.twoSum(nums, target)))
print('result2:', self.solution2.twoSum(nums, target))
print('Solution3 Length:', len(self.solution3.twoSum(nums, target)))
print('result3:', self.solution3.twoSum(nums, target))
unittest.main()
得到结果
nums: [8, 0, 2, 15, 18, 5, 4, 14, 3, 12, 17, 19, 11, 10, 6, 16, 7, 13, 1, 9]
Solution Length: 4
result: [[18, 12], [14, 16], [17, 13], [19, 11]]
Solution2 Length: 8
result2: [[18, 12], [14, 16], [12, 18], [17, 13], [19, 11], [11, 19], [16, 14], [13, 17]]
Solution3 Length: 4
result3: [[12, 18], [11, 19], [16, 14], [13, 17]]
.
----------------------------------------------------------------------
Ran 3 tests in 0.001s
我是解决方案2的粉丝。
如何重写if nums_d.get(complement) != None and nums_d.get(complement) != i:
避免重复?
【问题讨论】:
标签: python python-3.x