题目:
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).
解题思路:
首先要将nums进行排序,然后从两端逼近比较,直到找到合适的result
class Solution:
# @param {integer[]} nums
# @param {integer} target
# @return {integer}
def threeSumClosest(self, nums, target):
result = nums[0]+nums[1]+nums[2]
nums.sort()
if len(nums)<4:
return result
for i in range(len(nums)):
low = i+1
high = len(nums)-1
while(low<high):
sum = nums[i]+nums[low]+nums[high]
if sum == target:
return sum
elif sum > target:
if(abs(sum-target)<abs(result-target)):
result = sum
high -= 1
else:
if(abs(sum-target)<abs(result-target)):
result = sum
low += 1
return result
# @param {integer[]} nums
# @param {integer} target
# @return {integer}
def threeSumClosest(self, nums, target):
result = nums[0]+nums[1]+nums[2]
nums.sort()
if len(nums)<4:
return result
for i in range(len(nums)):
low = i+1
high = len(nums)-1
while(low<high):
sum = nums[i]+nums[low]+nums[high]
if sum == target:
return sum
elif sum > target:
if(abs(sum-target)<abs(result-target)):
result = sum
high -= 1
else:
if(abs(sum-target)<abs(result-target)):
result = sum
low += 1
return result