leetcode 15. 三数之和

深碍√TFBOYSˉ_ 2022-05-14 07:51 287阅读 0赞

【前言】

  1. pythonleetcode题解答目录索引:[https://blog.csdn.net/weixin\_40449300/article/details/89470836][https_blog.csdn.net_weixin_40449300_article_details_89470836]
  2. github链接:[https://github.com/Teingi/test][https_github.com_Teingi_test]

【正文】

给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。

注意:答案中不可以包含重复的三元组。

  1. 例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],
  2. 满足要求的三元组集合为:
  3. [
  4. [-1, 0, 1],
  5. [-1, -1, 2]
  6. ]

解法:对数组先进行排序处理,一头一尾设置两个指针,注意去重

  1. class Solution:
  2. def threeSum(self, nums):
  3. """
  4. :type nums: List[int]
  5. :rtype: List[List[int]]
  6. """
  7. nums.sort()#排序
  8. res =[]
  9. i = 0
  10. for i in range(len(nums)):
  11. if i == 0 or nums[i]>nums[i-1]:
  12. l = i+1
  13. r = len(nums)-1
  14. while l < r:
  15. s = nums[i] + nums[l] +nums[r]
  16. if s ==0:
  17. res.append([nums[i],nums[l],nums[r]])
  18. l +=1
  19. r -=1
  20. while l < r and nums[l] == nums[l-1]:#避免相同值
  21. l += 1
  22. while r > l and nums[r] == nums[r+1]:
  23. r -= 1
  24. elif s>0:
  25. r -=1
  26. else :
  27. l +=1
  28. return res

发表评论

表情:
评论列表 (有 0 条评论,287人围观)

还没有评论,来说两句吧...

相关阅读

    相关 leetcode:15.之和

    题目描述: 给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元

    相关 LeetCode-15.之和

    题目 给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。