Given an array nums
of n integers, are there elements a, b, c in nums
such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:The solution set must not contain duplicate triplets.
给定一个包含 n 个整数的数组 nums
,判断 nums
中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
代码:
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
ret_list = []
countNumberSet = {}
countNumberSet = self.countNumber(nums)
for key, value in countNumberSet.items():
if(key == 0 and value>=3):
ret_list.append([0,0,0])
#下面三个条件的顺序也是有技巧的,虽然都是与操作,但是我们要考虑短路思想
#下面如果把 key != 0放到第一位,算法就会超时!!至少我提交的时候是这样的
elif(value >= 2 and key !=0 and (0-key-key) in nums):
temp = [key, key, 0-key-key]
temp.sort()
ret_list.append(temp)
#去掉所有重复数据,保证数据的唯一性
nums = list(set(nums))
if(len(nums) <= 2):
pass
else:
nums.sort()
for i in range(len(nums)):
left = i
middle = i + 1
right = len(nums) - 1
#如果左指针所指向的数据大于0,则说明后面所有的数据都大于0,则停止
#如果右指针所指向的数据少于0,则说明前面所有的数据都小于0,则停止
if(nums[left] > 0 or nums[right] < 0):
break;
while(middle < right):
if(nums[left] + nums[middle] + nums[right] == 0):
ret_list.append([nums[left], nums[middle], nums[right]])
middle += 1
right -= 1
elif(nums[left] + nums[middle] + nums[right] > 0):
right -= 1
else:
middle += 1
return ret_list
def countNumber(self, nums):
countNumberSet = {}
for i in nums:
if i not in countNumberSet.keys():
countNumberSet[i] = 0
countNumberSet[i] += 1
return countNumberSet
成功
执行用时: 1440 ms, 在3Sum的Python3提交中击败了30.55% 的用户
提交时间 | 状态 | 执行用时 | 语言 |
---|---|---|---|
几秒前 | 通过 | 1440 ms | python3 |
2 分钟前 | 超出时间限制 | N/A | python3 |