标签:tin 超时 col list begin ati 方法 reg 数组
问题:
# 给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重
# 复的三元组。
#
# 注意:答案中不可以包含重复的三元组。
方法一:BF(submit超时)
# leetcode submit region begin(Prohibit modification and deletion) class Solution(object): def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ nums.sort() res = [] length = len(nums) for i in range(length-2): if nums[i] != nums[i-1] or i == 0: for j in range(i+1, length-1): if nums[j] != nums[j-1] or j==i+1: for k in range(j+1, length): if nums[k] != nums[k-1] or k==j+1: if nums[i] + nums[j] + nums[k] == 0: res.append([nums[i], nums[j], nums[k]]) return res # leetcode submit region end(Prohibit modification and deletion)
方法二:排序+双指针(左右夹逼)
# leetcode submit region begin(Prohibit modification and deletion) class Solution(object): def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ nums.sort() res = [] length = len(nums) for i in range(length): if i > 0 and nums[i] == nums[i-1]: continue left, right = i + 1, length-1 while left < right: v = nums[i] + nums[left] + nums[right] if v < 0: left += 1 elif v > 0: right -= 1 else: res.append([nums[i], nums[left], nums[right]]) while left < right and nums[left] == nums[left+1]: left+=1 while left < right and nums[right] == nums[right-1]: right-=1 left += 1 right -= 1 return res # leetcode submit region end(Prohibit modification and deletion)
标签:tin 超时 col list begin ati 方法 reg 数组
原文地址:https://www.cnblogs.com/demo-deng/p/14773590.html