class Solution: def threeSum(self, nums): n = len(nums) # 升序 下面去重要用到 nums.sort() res = [] # 找到三数之和等于0,只需要循环n-3次 for i in range(n - 2): # 去除邻近相同元素 if i > 0 and nums[i] == nums[i - 1]: continue # 建立双指针 l = i + 1 r = n - 1 while (l < r): if (nums[i] + nums[l] + nums[r] < 0): l = l + 1 elif (nums[i] + nums[l] + nums[r] > 0): r = r - 1 else: res.append([nums[i], nums[l], nums[r]]) # 去除邻近相同元素 防止添加的元素相同 while (l < r and nums[l] == nums[l + 1]): l = l + 1 while (l < r and nums[r] == nums[r - 1]): r = r - 1 l = l + 1 r = r - 1 return res res = Solution() print(res.threeSum([-1, 0, 0, 1, 1, 2, 2, -1, 4]))
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)