您的位置:首页 > 其它

leetcode 16. 3Sum Closest

2016-05-04 14:53 197 查看
import java.util.Arrays;

//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 static void main(String[] args) {
int[] a = {1,1,1,1};
int result = threeSumClosest(a,-100);
System.out.println(result);
}

public static int threeSumClosest(int[] nums, int target) {
int result = 0;
int cha = 1000;
Arrays.sort(nums);															//先对数组排序
for(int i = 0;i<nums.length-2;i++){											//与上一题差不多,遍历数组,从当前元素之后的元素段首尾相加:1(当前),1(首),1,1(尾)
int j = i+1;
int end = nums.length-1;
while(j<end){															//首小于尾时循环
if(nums[i]+nums[j]+nums[end] == target){
return target;
}else if(nums[i]+nums[j]+nums[end]<target){							//根据三数相加与target的差值调整首尾的位置
if(cha>Math.abs(target-nums[i]-nums[j]-nums[end])){
cha = Math.abs(target-nums[i]-nums[j]-nums[end]);
result = nums[i]+nums[j]+nums[end];
}
j++;
}else{
if(cha>Math.abs(target-nums[i]-nums[j]-nums[end])){
cha = Math.abs(target-nums[i]-nums[j]-nums[end]);
result = nums[i]+nums[j]+nums[end];
}
end--;
}
}
}
return result;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: