LeetCode 第十六题 最接近的三数之和
给定一个包括 n 个整数的数组 S,找出 S 中的三个整数使得他们的和与给定的数 target 最接近。返回这三个数的和。假定每组输入只存在一个答案。
例如,给定数组 S = {-1 2 1 -4}, 并且 target = 1.与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).
Java
public static int threeSumClosest(int[] nums, int target) {
int result = 0;
if (nums.length <= 3) {
for (int i : nums)
result += i;
return result;
}
Arrays.sort(nums);
result = nums[0] + nums[1] + nums[2];
for (int i = 0; i < nums.length - 2; i++) {
int low = i + 1, high = nums.length - 1;
while (low < high) {
int current_sum = nums[i] + nums[low] + nums[high];
if (Math.abs(target - current_sum) < Math.abs(target - result)) {
result = current_sum;
if (result == target)
return target;
}
if (current_sum > target)
high--;
else
low++;
}
}
return result;
}
Python
class Solution(object):
def threeSumClosest(self, nums, target):
if len(nums) <= 3:
return sum(nums)
nums = sorted(nums)
result = nums[0] + nums[1] + nums[2]
for i in range(len(nums) - 2):
low, high = i + 1, len(nums) - 1
while (low < high):
current_sum = nums[i] + nums[low] + nums[high]
if (abs(target - current_sum) < abs(target - result)):
result = current_sum
if (result == target):
return result
if (current_sum > target):
high = high - 1
else:
low = low + 1
return result
C++
class Solution
{
public:
int threeSumClosest(vector<int>& nums, int target)
{
int result=0;
if(nums.size()<=3)
{
for(int i=0; i<nums.size(); i++)
{
result+=nums[i];
}
return result;
}
sort(nums.begin(),nums.end());
result=nums[0]+nums[1]+nums[2];
for(int i=0; i<nums.size()-2; i++)
{
int low=i+1,high=nums.size()-1;
while(low<high)
{
int current_sum=nums[i]+nums[low]+nums[high];
if(abs(target-current_sum)<abs(target-result))
{
result=current_sum;
if(result==target)return result;
}
if(current_sum>target)
high--;
else
low++;
}
}
return result;
}
};