【题目】
【思路】
两次for循环,查找第三个数thrid = -nums[i] - nums[j] ,判断剩下的数组中是否存在第三个数。
【python】
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
third = 0
ans = []
for i in range(len(nums)-1):
for j in range(i+1,len(nums)):
print(nums[i],nums[j])
third = -nums[i] - nums[j]
print('third:',third)
nums2 = nums[j+1:len(nums)]
print('rest list:',nums2)
if third in nums2:
ans.append([nums[i],nums[j],third])
return ans
s=[-1,0,1]
solution = Solution()
ans = solution.threeSum(s)
print ('return:',ans)
【调试】
-1 0
third: 1
rest list: [1]
-1 1
third: 0
rest list: []
0 1
third: -1
rest list: []
ans: [[-1, 0, 1]]
【LeetCode执行错误】
算法还未完善,会出现输出一样三个数的情况,今天晚点去解决= =