三数之和 leetcode python编程

 

Given an array nums of n integers, are there elements abc 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 mspython3
2 分钟前超出时间限制N/Apython3

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值