【题目】
15. 三数之和_python
【思路】
两次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执行错误】
15. 三数之和_python
算法还未完善,会出现输出一样三个数的情况,今天晚点去解决= =

相关文章:

  • 2021-12-09
  • 2022-01-09
  • 2021-12-28
  • 2021-07-28
  • 2021-11-14
  • 2021-08-21
  • 2021-08-01
  • 2021-06-23
猜你喜欢
  • 2020-04-06
  • 2021-06-06
  • 2021-11-18
  • 2022-01-09
  • 2022-02-28
相关资源
相似解决方案