3Sum Closest解题报告

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jining11/article/details/82561386

题目

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

猜你喜欢

转载自blog.csdn.net/jining11/article/details/82561386