双指针——最接近的三数之和,细节处理还是很关键的

59. 最接近的三数之和

中文
English

给一个包含 n 个整数的数组 S, 找到和与给定整数 target 最接近的三元组,返回这三个数的和。

样例

例1:

输入:[2,7,11,15],3
输出:20
解释:
2+7+11=20

例2:

输入:[-1,2,1,-4],1
输出:2
解释:
-1+2+1=2

挑战

O(n^2) 时间, O(1) 额外空间。

注意事项

只需要返回三元组之和,无需返回三元组本身

 

class Solution:
    """
    @param numbers: Give an array numbers of n integer
    @param target: An integer
    @return: return the sum of the three integers, the sum closest target.
    """
    def threeSumClosest(self, numbers, target):
        # write your code here
        numbers.sort()

        s = diff = float('inf')

        def find_nearest(arr, k, t, n):
            nonlocal s,diff
            l, r = k, len(arr) - 1
            while l < r:
                if arr[l] + arr[r] > t:
                    if arr[l] + arr[r] - t < diff:
                        s = arr[l] + arr[r] + n
                        diff = arr[l] + arr[r] - t
                    r -= 1
                else:
                    if t - arr[l] - arr[r] < diff:
                        s = arr[l] + arr[r] + n
                        diff = t - arr[l] - arr[r]
                    l += 1
            return s

        for i, n in enumerate(numbers):
            if i > 0 and numbers[i] == numbers[i - 1]:
                continue
            find_nearest(numbers, i + 1, target - n, n)

        return s

 

posted @ 2021-01-12 22:32  bonelee  阅读(108)  评论(0编辑  收藏  举报