3Sum Closest解题报告

题目

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
        """
        result = nums[0] + nums[1] + nums[2]
        min = abs(result-target)
        for i in range(len(nums)-2):
            for j in range(i+1,len(nums)-1):
                for k in range(j+1,len(nums)):
                    if abs(nums[i]+nums[j]+nums[k]-target) < min:
                        result = nums[i]+nums[j]+nums[k]
                        min = abs(nums[i]+nums[j]+nums[k]-target)
        return result

思路太简单就不说了,然后就被time limit打了脸,做题果然是要多想想才行。

解法二:端点法

参考了一下大佬的做法,果然还是端点大法好。。。上次掉了一次坑,这次又掉了进去。

class Solution(object):
    def threeSumClosest(self, nums, target):
        result = nums[0] + nums[1] + nums[2]
        min = abs(result-target)
        nums.sort()
        # 分i = 0和i > 0 的情况分别进行讨论
        for i in range(len(nums) - 2):
            if i > 0 and nums[i] == nums[i-1]:
                continue # 一模一样的情况就不需要分析了
                # 端点运动开始
            start = i + 1
            end = len(nums) - 1
            while start < end:
                value = nums[i] + nums[start] + nums[end]
                if abs(value - target) < min:
                    result = value
                    min = abs(value - target)
                if value == target:
                    return result
                elif value > target:
                    end = end - 1
                else:
                    start = start + 1
        return result

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

羊城迷鹿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值