我刚开始尝试使用LeetCode来提高我的Python编程技能。在这个经典问题中,我的代码无法通过一个测试用例。
问题描述如下:
给定一个整数数组,返回两个数字的索引,使它们相加等于特定目标。
您可以假设每个输入都只有一种解决方案,并且您不可以重复使用相同的元素。
示例:
给定nums = [2, 7, 11, 15],target = 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]上输出为空,因此索引1和2甚至没有被汇总,是否我错误地赋值了y?