您的位置:首页 > 其它

Leetcode 16 3Sum Closest

2015-07-26 00:09 393 查看

3Sum Closest

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


Solution1

和3 Sum问题一样,都是固定第一个数然后再去扫描剩余的两个数。这里比3 Sum好处理的地方只需要计算绝对值而不需要去考虑重复的情况。代码如下:

import java.util.Arrays;
public class Solution {
public int threeSumClosest(int[] nums, int target) {
long result = Integer.MAX_VALUE;//需要将result定义成long类型,因为有可能下面在相减的时候超出范围
Arrays.sort(nums);
for(int i=0;i<nums.length;i++){
for(int k=i+1,j=nums.length-1;k<j;){
int temp = nums[i] + nums[j] + nums[k];
if(Math.abs(temp-target)<Math.abs(result-target)) result = temp;
if(temp<target) k++;
else j--;
}
}
return (int)result;
}
}


Solution2

解法一在定义result的时候将其定义成为了一个long类型的数据,如果觉得这种定义很不优雅的话,也可以用如下的方式:

import java.util.Arrays;
public class Solution {
public int threeSumClosest(int[] nums, int target) {
int n = nums.length;
Arrays.sort(nums);
int result = nums[0]+nums[1]+nums[n-1];//先将result赋值为第一个能找到的
for(int i=0;i<n-2;i++){
for(int k=i+1,j=n-1;k<j;){
int temp = nums[i] + nums[j] + nums[k];
if(Math.abs(temp-target)<Math.abs(result-target)) result = temp;
if(temp<target) k++;
else j--;
}
}
return result;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode