給定一個包含 n 個整數的數組 nums,判斷 nums 中是否存在三個元素 a,b,c ,使得 a + b + c = 0 ?找出全部知足條件且不重複的三元組。數組
注意:答案中不能夠包含重複的三元組。app
例如, 給定數組 nums = [-1, 0, 1, 2, -1, -4],指針
知足要求的三元組集合爲:
[
[-1, 0, 1],
[-1, -1, 2]
]code
class Solution(object): def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ nums.sort() res = [] for k in range(len(nums) - 2): if nums[k] > 0: #確定不會超過buns break if k > 0 and nums[k] == nums[k - 1]: continue #跳過已經存在的數組 i, j = k + 1, len(nums) - 1 while i < j: s = nums[k] + nums[i] + nums[j] if s < 0: #小了,前指針向後移 i += 1 while i < j and nums[i] == nums[i - 1]: i += 1#找到一個不同的 elif s > 0:#大了,後指針向前移 j -= 1 while i < j and nums[j] == nums[j + 1]: j -= 1 #找到一個不同的 else: res.append([nums[k], nums[i], nums[j]]) i += 1 j -= 1 while i < j and nums[i] == nums[i - 1]: i += 1 #找到一個不同的 while i < j and nums[j] == nums[j + 1]: j -= 1 #找到一個不同的 return res
class Solution(object): def threeSum(self, nums): dic = {} res = [] for i in nums: dic[i] = dic.get(i,0) + 1 pos = [i for i in dic if i > 0] neg = [i for i in dic if i < 0] neg.sort() if 0 in dic and dic[0] >= 3: res.append([0,0,0]) for i in pos: for j in neg: k = -i-j if k in dic: if (k==i or k==j) and dic[k] >= 2: res.append([i,k,j]) elif i > k > j: res.append([i,k,j]) if k < j: break return res ''' nums.sort() n = len(nums) ls = [] for i in range(n): left = i+1 right = n-1 if i > 0 and nums[i] == nums[i-1]: left += 1 continue while left < right: s = nums[i] + nums[left] + nums[right] if s == 0: col = [nums[i],nums[left],nums[right]] ls.append(col) left += 1 right -= 1 while nums[left] == nums[left-1] and left < right: left+=1 while nums[right] == nums[right+1] and left < right: right-=1 if s < 0: left += 1 elif s > 0: right -= 1 return ls ''' """ :type nums: List[int] :rtype: List[List[int]] """