【LeetCode】16.最接近的三数之和

#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time: 2019/3/14
# @Author: xfLi
# The file...

"""
问题分析:
与15题相似,可以先从小到大排序,然后固定一个值,从这个值的右区间开始,设置两个指针 left,  right向最近值逼近。
(1)对nums从小到大排序。
(2)遍历(或者是枚举)取出一个值,并确定右区间和指针 left, right。
(3)更新最优值,已经根据当前三个数的和,移动指针 left, right。
(4)继续(2)(3)直至结束。
"""

def threeSumClosest(nums, target):
    nums.sort()
    closest_sum = nums[0] + nums[1] + nums[2]
    for i in range(len(nums) - 2):
        left, right = i + 1, len(nums) - 1
        while left < right:
            sums = nums[i] + nums[left] + nums[right]
            if sums == target: return sums
            if abs(sums - target) < abs(closest_sum - target):
                closest_sum = sums
            if sums > target:
                right -= 1
            if sums < target:
                left += 1
    return closest_sum

if __name__ == '__main__':
    nums = [-1, 2, 1, -4]
    target = 1
    result = threeSumClosest(nums, target)
    print(result)

猜你喜欢

转载自blog.csdn.net/qq_30159015/article/details/88558582