LeetCode 3Sum Closest 三数求和最接近目标
试题:
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).
代码:
和3sum一样解法
class Solution {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int closest = 0x3f3f3f3f;
int out=0;
for(int i=0; i<nums.length; i++){
int curtarget = target-nums[i];
int f=i+1,t=nums.length-1;
while(f<t){
// System.out.println(" "+nums[i]+" "+nums[f]+" "+nums[t]);
int sum = nums[f] + nums[t];
int close = Math.abs(curtarget-sum);
if(closest>close){
closest = close;
out = nums[i] + nums[f] +nums[t];
}
if(curtarget<=sum){
t--;
}else if(curtarget>sum){
f++;
}
}
}
return out;
}
}
还没有评论,来说两句吧...