首页 > 学院 > 开发设计 > 正文

[Leetcode] 16. 3Sum Closest

2019-11-11 05:58:46
字体:
来源:转载
供稿:网友

PRoblem:

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

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).

思路: 这道题与前一道15题3Sum是相似的,直接用3Sum里提到的那两种方法之一皆可。唯一不同的是还需要一个统计参数sum来记录最接近target值的三个数和,然后每一次循环需要比较当前三个数的和tmpsum与统计参数sum到target的绝对值,借此更新统计参数sum。

Solution:

class Solution(object): def threeSumClosest(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ ressum = 0 delta = 0 nums.sort() numslen = len(nums) if numslen < 3: return ressum else: ressum = nums[0]+nums[1]+nums[2] delta = abs(target - ressum) i = 0 for i in xrange(0,numslen-2): indexi = i+1 indexj = numslen-1 while indexi < indexj: tmp = target - nums[i] - nums[indexi] - nums[indexj] if abs(tmp) < delta: delta = abs(tmp) ressum = target - tmp if tmp > 0 : indexi += 1 elif tmp < 0: indexj -= 1 else: break return ressum
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表