[LeetCode] 3Sum Closest 最近的三数之和 Python

3Sum Closest:

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

简单来说,寻找三数之和最接近target的答案,例子如下:

 For example, given array S = {-1 2 1 -4}, and target = 1.

 The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

 解决方法:


和 上一篇3Sum的想法类似,因此代码也是在那个的基础上修改的。只不过因为需要求最近的,而不是固定的,因此所有的判定都需要修改为判断与与target做差后的绝对值, 因为代码大构架和3Sum类似,因此时间复杂度还是O(N^2),代码如下:

class Solution(object):
    def threeSumClosest(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        nums.sort()
        first=[]
        i=0
        Max=0
        while(iright and nums[left]+nums[right]+nums[i]>target):
                            right-=1
                            if(nums[right]!=nums[right+1]):
                                break
                    elif(nums[left]+nums[right]+nums[i]>target):
                        right-=1
                    elif(nums[left]+nums[right]+nums[i]


你可能感兴趣的:(Python,算法基础,LeetCode)