• En
  • Signup
  • 刷题上岸
  • Today 0
  • Post 12
  • Followed 1
  • 捐助

    请在小工具里添加二维码

    刷题上岸 刷题上岸 关注:1 内容:12

    15. 3Sum

  • 查看作者
  • 打赏作者
  • 拉黑名单
    • 刷题上岸
    • 等级6
      土豪

      Given an array nums of n integers, are there elements abc in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

      Note:

      The solution set must not contain duplicate triplets.

      Example:

      Given array nums = [-1, 0, 1, 2, -1, -4],
      
      A solution set is:
      [
        [-1, 0, 1],
        [-1, -1, 2]
      ]

      class Solution:
          def threeSum(self, nums: List[int]) -> List[List[int]]:
              nums.sort()
              res = set()
              print(nums)
              for index in range(len(nums)):
                  
                  i = index +1
                  j = len(nums)-1
                  
                  while i < j:
                      
                      if (nums[index] + nums[i] + nums[j]) > 0:
                          j -= 1
                      elif (nums[index] + nums[i] + nums[j]) < 0:
                          i += 1
                      else:
                          
                          
                          res.add((nums[index] , nums[i] , nums[j]))
                          j-=1
                          i+=1
                         
              return list(res)

                          

      请登录之后再进行评论

      登录
    • Tasks
    • Current Activities
    • Back to Top