这是对LeetCode的练习。我得到的除了
第15行的UnboundLocalError。
为什么呢?以及如何解决它?
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]
答案 0 :(得分:1)
我相信这会起作用:
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 :(得分:0)
可能是你试试的:
if self.nums[i] + self.nums[j] == target:
# ^^^^^ ^^^^^
答案 2 :(得分:0)
让我们检查你的代码:
第一种情况(没有组合与目标匹配)
该方法返回一个尚未定义的值:
return a[i, j]
但a
从未被定义过!
第二种情况(组合匹配目标)
该方法返回一个初始化的值:
a = []
但是,我们从未在索引[i, j]
处设置值,因此这仍然不起作用:
return a[i, j]
<强>解决方案强>
当您找到等于目标的组合时,请返回其索引:
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)
答案 3 :(得分:0)
看看这是否有帮助...返回所有可能的索引:
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]
通话方式:
getIndices(<your-list>, <your-target>)
示例:
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) => []