题目如下:
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).
代码如下:
public class Solution {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int len=nums.length;
int closet=nums[0]+nums[1]+nums[2];
for(int i=0;i<len-2;i++){
int l=i+1;//left
int r=len-1;//right
/*if(l==r-1){
closet=Math.abs(closet-target)<Math.abs(nums[i]+nums[l]+nums[r]-target)?closet:nums[i]+nums[l]+nums[r];
continue;
}*/
while(l<r-1){
if(closet==target)return closet;
int a=nums[i]+nums[l]+nums[r]-target;
if(nums[l]+nums[r]<target-nums[i])
l++;
else r--;
int b=nums[i]+nums[l]+nums[r]-target;
if(a*b<0){
int min=Math.abs(a)<Math.abs(b)?a:b;
closet=Math.abs(closet-target)<Math.abs(min)?closet:min+target;
continue;
}
}
closet=Math.abs(closet-target)<Math.abs(nums[i]+nums[l]+nums[r]-target)?closet:nums[i]+nums[l]+nums[r];
}
return closet;
}
}public class Solution {
public int threeSumClosest(int[] num, int target) {
int min = Integer.MAX_VALUE;
int result = 0;
Arrays.sort(num);
for (int i = 0; i < num.length; i++) {
int j = i + 1;
int k = num.length - 1;
while (j < k) {
int sum = num[i] + num[j] + num[k];
int diff = Math.abs(sum - target);
if(diff == 0) return sum;
if (diff < min) {
min = diff;
result = sum;
}
if (sum <= target) {
j++;
} else {
k--;
}
}
}
return result;
}
}
本文介绍了一种算法,用于从整数数组中找出三个数,使其和最接近给定的目标值。通过排序和双指针技巧,有效地解决了这一问题。
123

被折叠的 条评论
为什么被折叠?



