Given an array nums
of n integers and an integer target
, find three integers in nums
such that the sum is closest to target
. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Example:
Given array nums = [-1, 2, 1, -4], and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
解题思路:
由于需要找出三个这样的数,因此维护三个下标i,j,k,我们可以先对这个列表进行排序。第一个下标i从0移动到n-1,对于每一个下标i,设定j的初始值为i+1,k的初始值为n-1,j和k的移动方式遵循以下规则:若三个数的和大于目标值target,则j增加1,否则k减少1,直到j与k相等为止。由于列表已经是排好序的,因此此做法是正确的。对于每一组这样的i,j,k,可以找出与目标值target相差最小的和值,其时间复杂度为O(n^2),比暴力解法的时间复杂度O(n^3)要低。
代码
class Solution:
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
nums.sort()
closest_sum = nums[0]+nums[1]+nums[2]
distance = abs(closest_sum-target)
n = len(nums)
for i in range(0,len(nums)-2):
j = i+1;
k = n-1;
while(j