Python两次求和-蛮力法
问题内容:
我是Python的新手,刚刚开始尝试LeetCode来构建我的排骨。关于这个经典问题,我的代码错过了一个测试用例。
问题如下:
给定一个整数数组,返回两个数字的索引,以便它们加起来成为一个特定的目标。
您可以假设每个输入都只有一个解决方案,并且您可能不会两次使用同一元素。
例:
给定nums = [2,7,11,15],目标= 9,
因为nums [0] + nums [1] = 2 + 7 = 9,所以返回[0,1]。
我错过了目标编号为6的测试用例[3,2,4],它应该返回索引[1,2],但是在目标编号为6的测试用例[1,5,7]上击中了(当然哪个返回索引[0,1]),所以在while循环中似乎出了点问题,但是我不太确定是什么。
class Solution:
def twoSum(self, nums, target):
x = 0
y = len(nums) - 1
while x < y:
if nums[x] + nums[y] == target:
return (x, y)
if nums[x] + nums[y] < target:
x += 1
else:
y -= 1
self.x = x
self.y = y
self.array = array
return None
test_case = Solution()
array = [1, 5, 7]
print(test_case.twoSum(array, 6))
输出在目标为6的测试用例[3,2,4]上返回null,因此甚至没有汇总索引1和2,我可以为y分配错误吗?
问题答案:
有点不同的方法。我们将根据需要构建一个值字典,该字典由我们要查找的值构成键;如果我们寻找一个值,则会在该值首次出现时对其进行索引。一旦找到满足问题的值,就可以完成。这个时间也是O(N)
class Solution:
def twoSum(self, nums, target):
look_for = {}
for n,x in enumerate(nums):
try:
return look_for[x], n
except KeyError:
look_for.setdefault(target - x,n)
test_case = Solution()
array = [1, 5, 7]
array2 = [3,2,4]
given_nums=[2,7,11,15]
print(test_case.twoSum(array, 6))
print(test_case.twoSum(array2, 6))
print(test_case.twoSum(given_nums,9))
输出:
(0, 1)
(1, 2)
(0, 1)