16. 3Sum Closest (python)

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.
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).
题意:在数组S中找到三个元素相加和最接近目标值,只有一组解,返回三元素的和
思路:类似于15的思路,做稍许改动,先任意取三元素和triple;记录和目标的差值diff
每次取一个数,在后续列表中找2sum满足三数之和最接近target,通过判断三数之和和目标的差值和diff大小,小于diff则将三数之和和差值赋值给triple和diff,然后再分析和小于移动左指针,大于移动右指针,直到遍历找到最接近的数
注意:不能先比较三数之和和目标值大小移动左右指针,遍历完才计算差值。而应该每次移动指针后都要计算差值,取差值最小的三数之和存储。
举例说明:若目标值为0,三数之和为-1,需要移动左指针,假设移动后此时三数之和为2,那么计算时就会比较2而不是1和目标的差值。因此要在移动指针后就要计算差值,-1是计算一次,2时计算一次。
Runtime: 122 ms

class Solution(object):
    def threeSumClosest(self, nums, target):
        if len(nums)<3:
            return  []
        nums=sorted(nums)
        triple=nums[0]+nums[1]+nums[-1]          #三数最接近目标值之和
        diff=abs(target-triple)
        for i in range(0,len(nums)-2):
            if nums[i]!=nums[i-1] or i==0:       #去重
                l,r=i+1,len(nums)-1  
                while  l#三数之和和目标值的偏差
                    if dif s==target:
                        return  target
                    elif s1
                    else:
                        r-=1
        return  triple  

你可能感兴趣的:(leetcode)