排序后循环遍历,固定index位置,然后双指针移动,避免重复的时候,注意比较索引的位置是走过的位置。
# 给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复# 的三元组。## 注意:答案中不可以包含重复的三元组。#### 示例:## 给定数组 nums = [-1, 0, 1, 2, -1, -4],## 满足要求的三元组集合为:# [# [-1, 0, 1],# [-1, -1, 2]# ]## Related Topics 数组 双指针# 👍 2486 👎 0# leetcode submit region begin(Prohibit modification and deletion)class Solution(object):def threeSum(self, nums):""":type nums: List[int]:rtype: List[List[int]]"""res = []nums.sort()for index, item in enumerate(nums):# 有重复的时候,只计算一个if index > 0 and nums[index] == nums[index - 1]:continueleft, right = index + 1, len(nums) - 1while left < right:sum_tmp = item + nums[left] + nums[right]if sum_tmp == 0:res.append([item, nums[left], nums[right]])left += 1right -= 1# 判断条件一定要是left比较左侧,right比较右侧,避免重复while left < right and nums[left] == nums[left - 1]:left += 1while left < right and nums[right] == nums[right + 1]:right -= 1elif sum_tmp > 0:right -= 1elif sum_tmp < 0:left += 1return res# leetcode submit region end(Prohibit modification and deletion)s = Solution()print(s.threeSum([0, 0, 0]))print(s.threeSum([-1, 0, 1, 2, -1, -4]))
