LeetCode15.三数之和

题目:

给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。

注意:答案中不可以包含重复的三元组。

例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],

满足要求的三元组集合为:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

解法一,复杂度O(n^3),TLE:这是最容易的逻辑了显然会超时,过于复杂

class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        nums.sort()
        flag =[]
        result = []
        leng = len(nums)
        for i in range(leng):
            for j in range(i+1,leng):
                for k in range(j+1,leng):
                    if (nums[i]+nums[j]+nums[k]==0):
                        flag=[nums[i],nums[j],nums[k]]
                        flag.sort()
                        if (flag not in result):
                            result.append(flag)
        return result

解法二:参考了其他人的思路,即两者相加会等于第三个数的相反数这个逻辑

class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        result = []
        nums.sort()
        leng = len(nums)
        for i in range(leng-2):
            if i == 0 or nums[i] > nums[i-1]:
                left = i+1
                right = len(nums)-1
                while left < right:
                    flag = nums[left] + nums[right] + nums[i]
                    if flag == 0:
                        result.append([nums[i], nums[left], nums[right]])
                        left += 1; right -= 1
                        while left < right and nums[left] == nums[left-1]:    
                            left += 1
                        while left < right and nums[right] == nums[right+1]:
                            right -= 1
                    elif flag < 0:
                        left += 1
                    else:
                        right -= 1
        
        return result

猜你喜欢

转载自blog.csdn.net/sweat2heart/article/details/82145141