LeetCode 3Sum Closest

来源:互联网 发布:python 字符串 查找 编辑:程序博客网 时间:2024/05/21 09:10

LeetCode解题之3Sum Closest


原题

找出一个列表中三个元素之和与目标值最接近的情况,并返回这个值。假设整个列表中只有一个最接近的值。

注意点:

  • 结果要求返回的是和,而不是三元组

例子:

输入: nums=[1, 1, 1, 1], target=-100
输出: 3

解题思路

思路与3Sum基本相同,现在要额外维护一个表示之前三元组中与目标值的差最小值的变量,这个变量的初始化值应该很大,防止把有意义的三元组直接排除了。此外,由于题目中明确说只有唯一的一组最优解,所有不用考虑重复数字了。

AC源码

class Solution(object):    def threeSumClosest(self, nums, target):        """        :type nums: List[int]        :type target: int        :rtype: int        """        nums.sort()        i = 0        result = 0        # Init the distance between result and target with a very large number        distance = pow(2, 32) - 1        for i in range(len(nums)):            j = i + 1            k = len(nums) - 1            while j < k:                l = [nums[i], nums[j], nums[k]]                if sum(l) == target:                    return target                if abs(sum(l) - target) < distance:                    result = sum(l)                    distance = abs(sum(l) - target)                elif sum(l) > target:                    k -= 1                else:                    j += 1        return resultif __name__ == "__main__":    assert Solution().threeSumClosest([1, 1, 1, 1], -100) == 3

欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。

0 0
原创粉丝点击