我是Python的新手,刚刚开始尝试LeetCode来构建我的排骨.在这个经典问题上,我的代码错过了一个测试用例.
问题如下:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [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分配错误吗?