leetcode之3Sum(15)

题目:

给定一个包含 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)的代码会超时,考虑用双指针将问题变成O(n^2).:

1.固定i,j、k为双向指针,j从头开始,k从尾开始遍历。

2.当和小于0时,j加1,当和大于0时,k减1

3.当找到一个值时,不能当做此时i的固定结果,因为可能有多个,所以需要再把j、k其中之一改变,j加1或者k减1都可以

python代码:

class Solution(object):
    def threeSum(self, nums):
        length = len(nums)
        resultList = []
        nums.sort()
        for i in range(0,length-2):
            j = i + 1
            k = length - 1
            while (j < k):
                sum0 = nums[i] + nums[j] + nums[k]
                if (sum0 == 0):
                    result = []
                    result.append(nums[i])
                    result.append(nums[j])
                    result.append(nums[k])
                    if result not in resultList:
                        resultList.append(result)
                    j +=1
                if (sum0 < 0):
                    j +=1
                if (sum0 > 0):
                    k -=1
        return resultList

猜你喜欢

转载自blog.csdn.net/cuicheng01/article/details/82351918