python leetcode编程作业2

题目:3Sum

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.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]


解题思路:

先选定一个数字a,则将问题转化为寻找两个数之和为-a的问题,故可以先将列表排序,然后从两端的数字开始求和,根据结果将符合要求的记下,并移动下标再作求和。时间复杂度为O(N*N)


代码:

class Solution:
    def threeSum(self, nums):
        nums = sorted(nums)
        result = []
        for i in range(len(nums)):
            if i!= 0 and nums[i] == nums[i-1]:
                continue
            front = i + 1
            back = len(nums) - 1
            while(front < back):
                if nums[i] + nums[front] + nums[back] < 0:
                    front += 1
                elif nums[i] + nums[front] + nums[back] > 0:
                    back -= 1
                else:
                    new_list = [nums[i], nums[front], nums[back]]
                    result.append(new_list[:])
                    f = front
                    b = back
                    while front < back and nums[front] == nums[f]:
                        front+= 1
                    while front < back and nums[back] == nums[b]:
                        back -= 1
        return result

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值