給定一個數組,選擇三個元素相加,結果必須爲全部三元組中最接近target的值,返回這個三元組的和。git
Given an array S of n integers, find three integers in S such that the sum is closest to a given number: target.github
Return the sum of the three integers. You may assume that each input would have exactly one solution.segmentfault
example 1數組
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). input: [-1, 2, 1, -4], 1 output: 2
思路參照三元組相加得到targetcode
只須要將上述文章思路2中換成:第二次循環找到 三元組的和 最接近target的組合便可。three
class Solution(object): def threeSumClosest(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ nums.sort() closest = nums[0] + nums[1] + nums[2] for i in range(len(nums)): j, k = i + 1, len(nums) - 1 while j < k: value = nums[i] + nums[j] + nums[k] closest = value if abs(target - value) < abs(target - closest) else closest if value == target: return target elif value > target: k -= 1 else: j += 1 return closest
本題以及其它leetcode題目代碼github地址: github地址leetcode