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;
}
};