对于LeetCode上的二和问题,它说:
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
Input: nums = [2,7,11,15], target = 9
Input: nums = [3,2,4], target = 6
Input: nums = [3,3], target = 6
这三个问题的结果都是:
[0,1]
[1,2]
[0,1]
但出于某种原因,我的代码未能通过最后一个测试用例并打印出来:
[0,1]
[1,2]
[]
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
temp = 0
tempValue = 0
for x in nums: # x is 3
temp = target - x # temp is 3
for y in nums: # y is 3
if nums.index(x) != nums.index(y):
tempValue = x + y # 3+3 = 6
if tempValue == target:
return [nums.index(x), nums.index(y)]