三数之和 leetcode python编程

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]
]

代码1:

class Solution:
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        tupleList = []
        listLen = len(nums)
        for i in range(listLen):
            for j in range(i+1,listLen,1):
                for k in range(j+1,listLen,1):
                    if (nums[i]+nums[j]+nums[k]) != 0 :
                        continue
                    else:
                         sortedList = sorted([nums[i],nums[j],nums[k]])
                         if sortedList not in tupleList:
                            tupleList.append(sortedList)
        return tupleList

提交记录

268 / 313  个通过测试用例
状态:

超出时间限制

 
提交时间: 1 周之前
最后执行的输入
[10,-2,-12,3,-15,-12,2,-11,3,-12,9,12,0,-5,-4,-2,-7,-15,7,4,-5,-14,-15,-15,-4,10,9,-6,7,1,12,-6,14,-15,12,14,10,0,10



好吧,超时了。虽然能得到结果,但是不满足要求,得改进!!


代码2:

class Solution:
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        tupleList = []
        nums.sort()
        index_greater_than_zero = self.indexGreaterThanZero(nums)
        listLen = len(nums)
        for i in range(index_greater_than_zero):
            for j in range(index_greater_than_zero,listLen,1):
                temp = 0 - nums[i] + nums[j]
                if temp in nums and [nums[i], nums[j], temp] not in tupleList:
                    tupleList.append([nums[i], nums[j], temp])
                else:
                    continue
        return tupleList
    
    def indexGreaterThanZero(self,nums):
        for index, value in enumerate(nums):
            if value>=0:
                return index
            else:
                continue
        return 0


提交记录

43 / 313  个通过测试用例
状态:

解答错误

 
提交时间: 2 分钟之前
输入: [-1,0,1,2,-1,-4]
输出: [[-1,0,1],[-1,1,2]]
预期: [[-1,-1,2],[-1,0,1]]





卧槽了,这也能算错


好吧,再修改


未完,待续


猜你喜欢

转载自blog.csdn.net/sxt1001/article/details/80718772