给一个包含 n 个整数的数组 S, 找到和与给定整数 target 最接近的三元组,返回这三个数的和。
样例
例如 S = [-1, 2, 1, -4]
and target = 1
. 和最接近 1 的三元组是 -1 + 2 + 1 = 2.
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 result = sum(numbers[:3]) -target for i in range(len(numbers)-2): for j in range(i+1,len(numbers)-1): for m in range(j+1,len(numbers)): tmp = numbers[i]+numbers[j]+numbers[m]-target if abs(result) > abs(tmp): result = tmp return result+target
时间复杂度o(n^3)
九章算法参考:
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): numbers.sort() ans = None for i in range(len(numbers)): l, r = i + 1, len(numbers) - 1 while (l < r): sum = numbers[l] + numbers[r] + numbers[i] if ans is None or abs(sum- target) < abs(ans - target): ans = sum if sum <= target: l = l + 1 else: r = r - 1 return ans
有点类似背包问题,放缩的比较好,提高了效率