From LeetCode Given an array of integers, return indices of the two numbers such that they add up to a specific target
这是一个关于leetcode的练习。我有个例外
UnboundLocalError on line 15.
为什么?如何修复?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ self.nums = [] self.target = int for i in range(len(nums)): for j in range(i + 1, len(nums)): if nums[i] + nums[j] == target: a = [] return a[i, j] |
我相信这是可行的:
1 2 3 4 5 6 7 8 9 10 11 12 | class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ n = len(nums) for i in range(n): for j in range(i+1, n): if nums[i] + nums[j] == target: return [i,j] |
看看这是否有帮助…返回所有可能的索引:
1 2 | def getIndices(tlist, target): return [(tlist.index(i), tlist.index(j)) for x,i in enumerate(tlist) for j in tlist[x:] if i!=j and i+j==target] |
如何称呼:
1 | getIndices(<your-list>, <your-target>) |
实例:
1 2 | getIndices([1,2,3,4,5,6,7,8], 10) => [(1, 7), (2, 6), (3, 5)] getIndices([1,2,3,4,5,6,7,8], 100) => [] |
让我们检查您的代码:
第一个场景(没有与目标匹配的组合)
该方法返回尚未定义的值:
1 | return a[i, j] |
但是,
第二种方案(组合与目标匹配)
方法返回一个已初始化的值:
1 | a = [] |
但是,我们从来没有在索引
1 | return a[i, j] |
解决方案
当找到与目标值相等的组合时,返回其索引:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ self.nums = [] self.target = int for i in range(len(nums)): for j in range(i + 1, len(nums)): if nums[i] + nums[j] == target: return i, j if __name__ =="__main__": a = Solution() print a.twoSum([1,2,3,4,5], 5) |
也许你会尝试一下:
1 2 | if self.nums[i] + self.nums[j] == target: # ^^^^^ ^^^^^ |