您的位置:首页 > 编程语言 > Java开发

【leetcode】【16】3Sum Closest

2016-02-28 09:34 477 查看

一、问题描述

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).

二、问题分析

此题和上一个3Sum基本一样,只不过判断条件有些许不同。

三、Java AC 代码

public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int closest = nums[0]+nums[1]+nums[nums.length-1];
for(int i = 0;i <= nums.length - 3; i++){
if(i==0 || nums[i]!=nums[i-1]){//remove duplicate
int start = i+1;
int end = nums.length-1;
while(start<end){
int sum = nums[i]+nums[start]+nums[end];
int tmp = sum - target;
if(Math.abs(closest-target)>Math.abs(tmp)) closest = sum;
if(Math.abs(tmp) == 0){
return sum;
}else if(tmp < 0){
start++;
}else if(tmp > 0){
end--;
}
}
}

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