15.3 sum & 16. 3Sum Closest

本文深入探讨了在给定整数数组中寻找三个数使它们的和为零或最接近目标值的问题,提供了两种解决方案:一是使用三层循环暴力求解;二是先排序数组,再运用双指针技巧进行高效搜索。文章通过实例详细阐述了每种方法的实现步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
1.三层循环暴力求解:

def threeSum(self, nums):
        length = len(nums)
        resultList = []
        for i in range(0,length):
            for j in range(i+1,length):
                for k in range(j+1,length):
                    tSum = nums[i] + nums[j] + nums[k]
                    if tSum == 0:
                        result = []
                        result.append(nums[i])
                        result.append(nums[j])
                        result.append(nums[k])
                        result.sort()
                        if result not in resultList:
                            resultList.append(result)
        return resultList

2.原数组排序,然后用两个指针夹逼

class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        res = []
        nums.sort()
        for i in xrange(len(nums)-2):
            if i > 0 and nums[i] == nums[i-1]:
                continue
            l, r = i+1, len(nums)-1
            while l < r:
                s = nums[i] + nums[l] + nums[r]
                if s < 0:
                    l +=1 
                elif s > 0:
                    r -= 1
                else:
                    res.append((nums[i], nums[l], nums[r]))
                    while l < r and nums[l] == nums[l+1]:
                        l += 1
                    while l < r and nums[r] == nums[r-1]:
                        r -= 1
                    l += 1; r -= 1
        return res

Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

Example:
Given array nums = [-1, 2, 1, -4], and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

class Solution(object):
    def threeSumClosest(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        res = 0
        diff = 2**32 - 1
        nums.sort()
        lens=len(nums)
        for i in range(lens-2):
            left=i+1
            right=lens-1
            while left<right:
                temp_sum=nums[i]+nums[left]+nums[right]
                temp_diff = abs(temp_sum-target)
                if temp_diff<diff:
                    res=temp_sum
                    diff=temp_diff
                if temp_sum<target:
                    left+=1
                elif temp_sum>target:
                    right-=1
                else:
                    return temp_sum
        return res
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值